@kriya-ai/harness 0.2.4 → 2.0.0

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 (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +49 -0
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +504 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +376 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +426 -0
  33. package/plugins/runstrip/index.js +301 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +82 -5
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +175 -3
  44. package/src/edit/core/plan.js +95 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/transitions.js +17 -0
  51. package/src/edit/core/type-kit.js +173 -0
  52. package/src/edit/director/ask.js +37 -3
  53. package/src/edit/director/assembly.js +829 -0
  54. package/src/edit/director/continuity.js +137 -0
  55. package/src/edit/director/custom-motion.js +88 -0
  56. package/src/edit/director/graphics.js +186 -0
  57. package/src/edit/director/intent.js +125 -0
  58. package/src/edit/director/mentions.js +52 -0
  59. package/src/edit/director/plan.js +89 -12
  60. package/src/edit/director/revise.js +172 -7
  61. package/src/edit/director/viewer.js +136 -0
  62. package/src/edit/director/watch-fix.js +119 -0
  63. package/src/edit/engine/captions.js +110 -5
  64. package/src/edit/engine/confine.js +81 -4
  65. package/src/edit/engine/custom.js +243 -0
  66. package/src/edit/engine/dna2.js +893 -0
  67. package/src/edit/engine/fonts.js +218 -0
  68. package/src/edit/engine/graphics.js +439 -0
  69. package/src/edit/engine/index.js +14 -5
  70. package/src/edit/engine/motion.js +153 -14
  71. package/src/edit/engine/music-bed.js +59 -1
  72. package/src/edit/engine/packs.js +11 -0
  73. package/src/edit/engine/reference2.js +26 -0
  74. package/src/edit/engine/sfx.js +56 -1
  75. package/src/edit/engine/tool.js +21 -5
  76. package/src/edit/gates/assembly.js +194 -0
  77. package/src/edit/gates/copy.js +7 -4
  78. package/src/edit/gates/index.js +76 -8
  79. package/src/edit/gates/picture.js +6 -3
  80. package/src/edit/gates/reference.js +115 -0
  81. package/src/edit/gates/tile.js +96 -0
  82. package/src/edit/host/client.js +4 -3
  83. package/src/edit/host/clips.js +33 -0
  84. package/src/edit/host/jobs.js +9 -3
  85. package/src/edit/host/layers.js +134 -0
  86. package/src/edit/host/main.js +17 -7
  87. package/src/edit/host/paths.js +34 -3
  88. package/src/edit/host/preview.js +108 -0
  89. package/src/edit/host/projects.js +494 -29
  90. package/src/edit/host/server.js +263 -19
  91. package/src/edit/host/tavi.js +77 -0
  92. package/src/edit/loop/make.js +44 -3
  93. package/src/edit/recipes/assembly.js +352 -0
  94. package/src/edit/recipes/graphic-clips.js +59 -0
  95. package/src/edit/recipes/openings.js +36 -0
  96. package/src/edit/recipes/reel.js +138 -17
  97. package/src/edit/recipes/reference-look.js +29 -0
  98. package/src/edit/recipes/short-from-long.js +3 -3
  99. package/src/edit/recipes/sound.js +71 -0
  100. package/src/edit/runtime/cli.js +26 -5
  101. package/src/edit/runtime/fetch.js +4 -3
  102. package/src/edit/runtime/licences.js +7 -1
  103. package/src/explore.js +103 -0
  104. package/src/failure.js +1 -1
  105. package/src/gate-commands.js +114 -0
  106. package/src/gates/api.js +127 -0
  107. package/src/gates/commands.js +111 -0
  108. package/src/gates/detectors.js +370 -0
  109. package/src/gates/http.js +62 -0
  110. package/src/gates/index.js +196 -0
  111. package/src/gates/page.js +264 -0
  112. package/src/gates/sast.js +64 -0
  113. package/src/gates/stack.js +110 -0
  114. package/src/gates/tenant.js +162 -0
  115. package/src/gates/three.js +407 -0
  116. package/src/gates/ui.js +111 -0
  117. package/src/launch.js +15 -3
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +32 -0
  122. package/src/orchestra.js +43 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +452 -3
  134. package/studio/dist/studio.js +3 -3
@@ -2,21 +2,37 @@
2
2
  // every request, and an owner-only socket with the same routes. Typed requests only:
3
3
  // no route runs a command, and every path passes guardPath.
4
4
 
5
- import { createHash, createHmac, randomBytes } from "node:crypto"
5
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"
6
6
  import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs"
7
7
  import { basename, dirname, extname, isAbsolute, join } from "node:path"
8
8
  import { pipeline } from "node:stream/promises"
9
9
 
10
+ import { apply, CRAFT_OP_NAMES, TYPE_OP_NAMES } from "../core/ops.js"
10
11
  import { compile } from "../core/plan.js"
12
+ import { clipNumbers } from "../core/project.js"
11
13
  import { solve } from "../core/solver.js"
12
- import { LOOKS } from "../engine/captions.js"
14
+ import { ALL_LOOKS, LOOKS, MORE_CAPTION_LOOKS } from "../engine/captions.js"
13
15
  import { ENGINE_VERSION, guardPath } from "../engine/index.js"
14
16
  import { cleanRefs } from "../engine/reference.js"
17
+ import { cleanOff } from "../core/style-brief.js"
15
18
  import { cleanScene } from "../engine/scenes.js"
19
+ import { ALL_GRAPHIC_KINDS, cleanGraphic, GRAPHIC_BLOCK, GRAPHIC_KINDS } from "../engine/graphics.js"
20
+ import { TRANSITIONS } from "../core/transitions.js"
21
+ import { regionOf } from "../core/effects.js"
16
22
  import { EngineFailure } from "../engine/tool.js"
17
23
  import { activeRuntime } from "../runtime/setup.js"
18
24
  import { recogniser } from "../index/layers/words.js"
25
+ import { assemblyProblems, isAssembly } from "../director/assembly.js"
19
26
  import { FORMATS, GRADES } from "../recipes/reel.js"
27
+ import { previewOf, tileDocument } from "./preview.js"
28
+ import { lastMadeEntry, layersOf, viewOf } from "./layers.js"
29
+ import { projectAt } from "../core/history.js"
30
+ import { TOKEN_HEADER } from "./paths.js"
31
+ import { withFonts } from "../engine/fonts.js"
32
+ import { applyStylePack, STYLE_PACKS } from "../core/style-packs.js"
33
+ import { cleanTypeKit, PAIRS } from "../core/type-kit.js"
34
+ import { ALL_MOODS, MOODS } from "../engine/music-bed.js"
35
+ import { CUT_SOUNDS, INTRO_SOUNDS } from "../engine/sfx.js"
20
36
 
21
37
  const HEADERS = {
22
38
  "cross-origin-opener-policy": "same-origin",
@@ -29,7 +45,8 @@ const COOKIE = "kriya_edit"
29
45
  const MAX_BODY = 4 * 1024 * 1024
30
46
  // The Studio app, built by `npm run build:studio` (ED6)
31
47
  const STUDIO = join(import.meta.dirname, "..", "..", "..", "studio", "dist")
32
- const STUDIO_FILES = { "/": ["index.html", "text/html; charset=utf-8"], "/studio.js": ["studio.js", "text/javascript"], "/studio.css": ["studio.css", "text/css"] }
48
+ // The Studio's three type faces (OFL-1.1, the harness's own: THIRD_PARTY_NOTICES.md), from this origin, so its policy stays 'self'
49
+ const STUDIO_FILES = { "/": ["index.html", "text/html; charset=utf-8"], "/studio.js": ["studio.js", "text/javascript"], "/studio.css": ["studio.css", "text/css"], "/fonts/geist.woff2": ["fonts/geist.woff2", "font/woff2"], "/fonts/fraunces.woff2": ["fonts/fraunces.woff2", "font/woff2"], "/fonts/jetbrains-mono.woff2": ["fonts/jetbrains-mono.woff2", "font/woff2"] }
33
50
  const TYPES = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".m4a": "audio/mp4", ".wav": "audio/wav", ".mp3": "audio/mpeg", ".jpg": "image/jpeg", ".json": "application/json" }
34
51
 
35
52
  // An inline icon, so the browser doesn't ask for /favicon.ico (a 404 in the console)
@@ -57,6 +74,30 @@ const backOf = (value, port) => {
57
74
  }
58
75
  }
59
76
 
77
+ // TP9: the longest cut a drawn box can point into (a day, in flicks); the Host checks it against the cut itself
78
+ const MARK_AT_MAX = 24 * 3600 * 705_600_000
79
+ const MARK_KINDS = ["box", "ring", "arrow"]
80
+
81
+ /**
82
+ * A box, ring or arrow drawn on the monitor (TP9, CRAFT_UPGRADE §7): never trusted as sent. Whole thousandths
83
+ * of the frame, inside it, each side at least 10; `at` whole flicks on the cut. @returns {object | null | undefined}
84
+ * undefined: none sent; null: sent and refused
85
+ */
86
+ export function cleanMark(raw) {
87
+ if (raw === undefined || raw === null) return undefined
88
+ if (typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).some((key) => !["kind", "x", "y", "w", "h", "at"].includes(key))) return null
89
+ if (!MARK_KINDS.includes(raw.kind) || !Number.isSafeInteger(raw.at) || raw.at < 0 || raw.at > MARK_AT_MAX) return null
90
+ const box = regionOf({ x: raw.x, y: raw.y, w: raw.w, h: raw.h })
91
+ return box ? { kind: raw.kind, ...box, at: raw.at } : null
92
+ }
93
+
94
+ /** A secret compared in constant time; anything but one string of the same length is no. */
95
+ export function sameSecret(given, secret) {
96
+ if (typeof given !== "string" || typeof secret !== "string") return false
97
+ const [a, b] = [Buffer.from(given), Buffer.from(secret)]
98
+ return a.length === b.length && timingSafeEqual(a, b)
99
+ }
100
+
60
101
  function studioFile(res, pathname) {
61
102
  const [name, type] = STUDIO_FILES[pathname]
62
103
  const file = join(STUDIO, name)
@@ -77,6 +118,22 @@ function page(res, type, body) {
77
118
  }
78
119
 
79
120
  const refuse = (res, status, message) => json(res, status, { error: status, message })
121
+ /** 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. */
122
+ // A plan's answered questions (TP4), so a revision doesn't ask again: up to 8 plain values, each checked again by readIntent
123
+ const cleanAnswers = (answers) => (answers && typeof answers === "object" && !Array.isArray(answers) ? Object.fromEntries(Object.entries(answers).filter(([key, value]) => /^[A-Za-z]{1,32}$/.test(key) && ["string", "number", "boolean"].includes(typeof value) && String(value).length <= 64).slice(0, 8)) : null)
124
+ 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 : {}, ...(cleanAnswers(plan.intent?.answers) ? { intent: { answers: cleanAnswers(plan.intent.answers) } } : {}) } : null)
125
+
126
+ /** A request's raw bytes, up to MAX_BODY. */
127
+ async function readBody(req) {
128
+ const chunks = []
129
+ let size = 0
130
+ for await (const chunk of req) {
131
+ size += chunk.length
132
+ if (size > MAX_BODY) throw new EngineFailure("input", "too_large", "That request is too large.")
133
+ chunks.push(chunk)
134
+ }
135
+ return Buffer.concat(chunks)
136
+ }
80
137
 
81
138
  async function readJson(req) {
82
139
  const chunks = []
@@ -122,7 +179,7 @@ const statusOf = (error) => ({ outside_project: 403, missing_file: 404, exists:
122
179
  */
123
180
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
124
181
 
125
- export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid, stamp = null, busy = () => 0 }) {
182
+ export function createHandler({ home, ipcToken = null, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid, stamp = null, busy = () => 0 }) {
126
183
  const tokens = new Map() // sha256 of a launch token → { expires, back }
127
184
  const sessions = new Set()
128
185
  const mediaSecret = randomBytes(32)
@@ -136,8 +193,23 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
136
193
 
137
194
  // offline: the file isn't where the project says, so the Studio asks to relink it (EG-3)
138
195
  const withMedia = (state, asset) => ({ ...asset, media: mediaId(state.id, asset.id), ...(existsSync(isAbsolute(asset.path) ? asset.path : join(state.folder, asset.path)) ? {} : { offline: true }) })
196
+ // TP1, only with editing.assembly on: each clip's computed number (never stored, EH-54) and the
197
+ // day its file was last written, for the bin's sort and groups. Off, the view is what it was
198
+ // shortcut: the file's own date stands in for "recorded" (a copied file gets the day it was copied); read the container's creation time when that matters
199
+ const withHandle = (state, numbers) => (asset) => {
200
+ const view = withMedia(state, asset)
201
+ if (!numbers.has(asset.id)) return view
202
+ const recorded = view.offline ? null : statSync(isAbsolute(asset.path) ? asset.path : join(state.folder, asset.path)).mtime.toISOString()
203
+ return { ...view, number: numbers.get(asset.id), ...(recorded ? { recorded } : {}) }
204
+ }
205
+ const assemblyOn = async () => (await projects.features()).assembly === true
206
+ const livePreviewOn = async () => (await projects.features()).livePreview === true
207
+ // Hold to talk (TP4): editing.intent on and the local recogniser's weights installed; otherwise no button and no route
208
+ const dictationOn = async () => (await projects.features()).intent === true && projects.canDictate()
139
209
  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." }
140
- 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] })) } : {}) })
210
+ // TP7: the type kit's choices, only with editing.typeKit on (labels only: fonts and colours stay in code), and whether this computer has the fonts
211
+ const typeKitView = async (state) => ((await projects.features()).typeKit === true ? { typeKit: { packs: Object.fromEntries(Object.entries(STYLE_PACKS).map(([id, pack]) => [id, { label: pack.label, does: pack.does }])), pairs: Object.fromEntries(Object.entries(PAIRS).map(([id, pair]) => [id, pair.label])), looks: Object.keys(MORE_CAPTION_LOOKS), shipped: (state.engine.motion().fonts?.size ?? 0) > 0, chosen: state.log.current.look.brand?.type ?? null } } : {})
212
+ const projectView = async (state) => ({ project: state.log.current, head: state.log.head, ...(await typeKitView(state)), ...((await livePreviewOn()) ? { livePreview: true } : {}), ...((await projects.features()).referenceIntent === true ? { referenceIntent: true } : {}), ...((await projects.features()).directorLoop === true ? { directorLoop: true } : {}), ...((await projects.features()).customMotion === true ? { customMotion: true } : {}), ...((await projects.features()).intent === true ? { intent: true, ...(projects.canDictate() ? { dictation: true } : {}) } : {}), ...((await assemblyOn()) ? { assembly: true, assets: state.log.current.assets.map(withHandle(state, clipNumbers(state.log.current))) } : { 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] })) } : {}) })
141
213
 
142
214
  // The Media Runtime, installed from the Studio with its progress shown (the same signed
143
215
  // manifest and checks as `kriya edit setup`): a first Index no longer looks like nothing happening
@@ -309,16 +381,25 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
309
381
  }
310
382
  const state = await needProject(res, parts[1])
311
383
  if (!state) return
312
- if (parts.length === 2 && method === "GET") return say(200, projectView(state))
384
+ if (parts.length === 2 && method === "GET") return say(200, await projectView(state))
313
385
  if (parts.length === 2 && method === "DELETE") return say(200, projects.remove(state.id, { running: (id) => jobs.runningIn(id) }))
314
386
  if (parts.length === 2 && method === "PATCH") {
315
387
  const { ops, undo } = await readJson(req)
316
388
  if (undo === true) {
317
389
  projects.undo(state)
318
- return say(200, { ...projectView(state), diagnostics: [] })
390
+ return say(200, { ...(await projectView(state)), diagnostics: [] })
391
+ }
392
+ // Labels and the storyboard are behind editing.assembly: off, the Host takes neither (ET-ASM-REG-01)
393
+ // Effects from the registry are behind editing.craft (TP5): off, the Host takes none
394
+ if (Array.isArray(ops) && ops.some((op) => CRAFT_OP_NAMES.includes(op?.op)) && (await projects.features()).craft !== true) return say(422, { ...(await projectView(state)), diagnostics: [{ code: "switched_off", message: "Effects aren't switched on.", op: 0 }] })
395
+ if (Array.isArray(ops) && ops.some((op) => ["describe_asset", "set_assembly", "place_over", "set_frame"].includes(op?.op)) && !(await assemblyOn())) return say(422, { ...(await projectView(state)), diagnostics: [{ code: "switched_off", message: "Clip labels and the storyboard aren't switched on.", op: 0 }] })
396
+ // The type kit, more caption looks and motion kit 2 are behind editing.typeKit (TP7): off, the Host takes none of them
397
+ if (Array.isArray(ops) && (await projects.features()).typeKit !== true) {
398
+ const typed = ops.findIndex((op) => TYPE_OP_NAMES.includes(op?.op) || (op?.op === "caption_style" && !Object.hasOwn(LOOKS, op.look ?? "") && Object.hasOwn(ALL_LOOKS, op.look ?? "")) || (op?.op === "add_motion" && op.block === GRAPHIC_BLOCK && (!Object.hasOwn(GRAPHIC_KINDS, op.variables?.kind ?? "") || !GRAPHIC_KINDS[op.variables.kind].styles.includes(op.variables?.style ?? GRAPHIC_KINDS[op.variables.kind].styles[0]))))
399
+ if (typed >= 0) return say(422, { ...(await projectView(state)), diagnostics: [{ code: "switched_off", message: "The type kit, the new caption looks and motion kit 2 aren't switched on.", op: typed }] })
319
400
  }
320
401
  const result = projects.change(state, { ops, author: "person" })
321
- return say(result.ok ? 200 : 422, { ...projectView(state), diagnostics: result.diagnostics })
402
+ return say(result.ok ? 200 : 422, { ...(await projectView(state)), diagnostics: result.diagnostics })
322
403
  }
323
404
  if (parts[2] === "assets" && method === "POST") {
324
405
  const { path } = await readJson(req)
@@ -339,27 +420,95 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
339
420
  const { picture, audio, overlays, captions, duration } = solve(state.log.current, state.index)
340
421
  return say(200, { ...compile(state.log.current, state.index, { engineVersion: ENGINE_VERSION, runtimeVersion: version }), timeline: { picture, audio, overlays, captions, duration } })
341
422
  }
423
+ // The live preview (TP3, editing.livePreview): what the monitor draws, from the draft's own plan;
424
+ // with ?proposal=, the cut as it would be if that proposal were accepted. Off, neither route exists
425
+ if (parts[2] === "preview" && parts.length === 3 && method === "GET") {
426
+ if (!(await livePreviewOn())) return refuse(res, 404, "The live preview isn't on.")
427
+ const proposalId = url.searchParams.get("proposal")
428
+ let project = state.log.current
429
+ if (proposalId !== null) {
430
+ const proposal = state.proposals.get(proposalId)
431
+ if (!proposal) return refuse(res, 404, "That proposal isn't there any more.")
432
+ const applied = apply(project, proposal.ops, { index: state.index })
433
+ if (applied.diagnostics.length) return refuse(res, 409, "That proposal no longer fits the cut.")
434
+ project = applied.project
435
+ }
436
+ const { version } = await tools()
437
+ state.previewTiles ??= new Map()
438
+ const fonts = state.engine.motion().fonts
439
+ return say(200, previewOf(project, state.index, { runtimeVersion: version, tiles: state.previewTiles, ...(fonts ? { fonts: [...fonts.keys()] } : {}) }))
440
+ }
441
+ // "Replay how it was edited" (editing.livePreview): the latest make's own operations, layer by layer,
442
+ // from the cut it started on, as previews to draw. Nothing renders and nothing is written
443
+ if (parts[2] === "layers" && parts.length === 3 && method === "GET") {
444
+ if (!(await livePreviewOn())) return refuse(res, 404, "The live preview isn't on.")
445
+ const { entry, job } = lastMadeEntry(state.journal.jobs("done"), state.log)
446
+ if (!entry) return refuse(res, 404, "There's no make to replay yet: make one first.")
447
+ const { version } = await tools()
448
+ state.previewTiles ??= new Map()
449
+ const fonts = state.engine.motion().fonts
450
+ const before = projectAt(state.log, entry.parent, { index: state.index })
451
+ const layers = layersOf(before, entry.ops, state.index).map(({ project, ...layer }) => ({ ...layer, ...viewOf(project, state.index, { runtimeVersion: version, tiles: state.previewTiles, ...(fonts ? { fonts: [...fonts.keys()] } : {}) }) }))
452
+ return say(200, { job, current: entry.id === state.log.head, layers })
453
+ }
454
+ // One tile of a preview: its own sandboxed document, no network, as the render draws it
455
+ if (parts[2] === "tile-preview" && parts.length === 3 && method === "GET") {
456
+ if (!(await livePreviewOn())) return refuse(res, 404, "The live preview isn't on.")
457
+ const found = tileDocument(state.previewTiles ?? new Map(), url.searchParams.get("key"))
458
+ if (found === null) return refuse(res, 404, "That tile isn't in this preview.")
459
+ // TP7: a type kit's fonts go in as data, as the render puts them; a tile without one is unchanged
460
+ const html = withFonts(found, state.engine.motion().fonts)
461
+ 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'; font-src 'self' data:; img-src 'self' data:; frame-ancestors 'self'; sandbox allow-scripts" })
462
+ return res.end(html)
463
+ }
464
+ // A few seconds of the person's voice to text, on this computer only (TP4, §7.4)
465
+ if (parts[2] === "dictate" && parts.length === 3 && method === "POST") {
466
+ if (!(await dictationOn())) return refuse(res, 404, "Hold to talk isn't available.")
467
+ if (!/^(?:audio|video)\/(?:webm|ogg|mp4)\b/.test(req.headers["content-type"] ?? "")) return refuse(res, 415, "Send the recording as WebM, Ogg or MP4 audio.")
468
+ const audio = await readBody(req)
469
+ if (!audio.length) return refuse(res, 400, "Nothing was recorded.")
470
+ return say(200, await projects.dictate(state, audio))
471
+ }
342
472
  if (parts[2] === "ask" && parts.length === 3 && method === "POST") {
343
- const { text, selection, history } = await readJson(req)
473
+ const { text, selection, history, mentions, mark: drawn } = await readJson(req)
344
474
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want changed, in up to 2,000 characters.")
475
+ // TP9: a drawn box, checked here; with editing.customMotion off it isn't read at all
476
+ const mark = (await projects.features()).customMotion === true ? cleanMark(drawn) : undefined
477
+ if (mark === null) return refuse(res, 400, "That drawing isn't a box, ring or arrow inside the frame. Draw it again.")
345
478
  // The chat's last turns, short and text only: nothing else of the browser's reaches the model
346
479
  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) })) : []
347
- return say(200, await projects.ask(state, { text, selection, history: turns }))
480
+ return say(200, await projects.ask(state, { text, selection, history: turns, mentions, ...(mark ? { mark } : {}) }))
481
+ }
482
+ // TP9 (editing.customMotion): a proposal's custom animation, as the render draws it: its own sandboxed document, no network
483
+ if (parts[2] === "custom-preview" && parts.length === 3 && method === "GET") {
484
+ if ((await projects.features()).customMotion !== true) return refuse(res, 404, "Custom motion isn't on.")
485
+ const n = Number(url.searchParams.get("op"))
486
+ if (!Number.isInteger(n) || n < 0) return refuse(res, 404, "That proposal has no custom animation to show.")
487
+ let html
488
+ try {
489
+ html = projects.customPreview(state, url.searchParams.get("proposal") ?? "", n)
490
+ } catch (error) {
491
+ if (error instanceof EngineFailure && error.reason === "no_preview") return refuse(res, 404, error.message)
492
+ throw error
493
+ }
494
+ 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" })
495
+ return res.end(html)
348
496
  }
349
497
  if (parts[2] === "proposals" && parts.length === 4 && method === "POST") {
350
498
  const { accept, only } = await readJson(req)
351
499
  if (typeof accept !== "boolean" || (only !== undefined && !(Array.isArray(only) && only.every(Number.isInteger)))) return refuse(res, 400, "Accept or reject the proposal.")
352
500
  const result = projects.decide(state, parts[3], { accept, only })
353
- return say(200, { ...result, ...projectView(state) })
501
+ return say(200, { ...result, ...(await projectView(state)) })
354
502
  }
355
503
  if (parts[2] === "make" && parts.length === 3 && method === "POST") {
356
- const { asset, brief } = await readJson(req)
504
+ const { asset, brief, plan } = await readJson(req)
357
505
  const clean = {}
358
506
  if (brief && typeof brief === "object") {
359
507
  if (Number.isFinite(brief.seconds) && brief.seconds >= 5 && brief.seconds <= 600) clean.targetDuration = Math.round(brief.seconds * 705_600_000)
360
508
  if (Array.isArray(brief.mustKeep) && brief.mustKeep.every((id) => typeof id === "string" && id.length < 64)) clean.mustKeep = brief.mustKeep.slice(0, 20)
361
509
  if (brief.effort === "fast" || brief.effort === "best") clean.effort = brief.effort
362
- if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
510
+ const typeKitOn = (await projects.features()).typeKit === true
511
+ if (typeof brief.captions === "string" && Object.hasOwn(typeKitOn ? ALL_LOOKS : LOOKS, brief.captions)) clean.captions = brief.captions
363
512
  if (typeof brief.music === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.music)) clean.music = brief.music
364
513
  if (typeof brief.reference === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.reference)) clean.reference = brief.reference
365
514
  if (Object.hasOwn(FORMATS, brief.format)) clean.format = brief.format
@@ -371,8 +520,11 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
371
520
  if (Array.isArray(brief.references)) clean.references = cleanRefs(brief.references)
372
521
  if (safeId(brief.hook)) clean.hook = brief.hook
373
522
  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 }
374
- if (["whoosh", "pop"].includes(brief.cutSound)) clean.cutSound = brief.cutSound
375
- if (["riser", "hit"].includes(brief.introSound)) clean.introSound = brief.introSound
523
+ // TP10: with editing.craft on, the sounds Kriya writes are more, and the make may arrange its sound to the cut
524
+ const crafted = (await projects.features()).craft === true
525
+ if ((crafted ? CUT_SOUNDS : ["whoosh", "pop"]).includes(brief.cutSound)) clean.cutSound = brief.cutSound
526
+ if ((crafted ? INTRO_SOUNDS : ["riser", "hit"]).includes(brief.introSound)) clean.introSound = brief.introSound
527
+ if (crafted) for (const flag of ["arrange", "ambience", "splits", "beatJoins"]) if (brief[flag] === true) clean[flag] = true
376
528
  if (Number.isInteger(brief.punches) && brief.punches >= 0 && brief.punches <= 8) clean.punches = brief.punches
377
529
  for (const flag of ["angles", "titles", "ramps"]) if (brief[flag] === true) clean[flag] = true
378
530
  if (brief.broll === "own") clean.broll = "own"
@@ -393,14 +545,76 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
393
545
  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 }))
394
546
  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 }))
395
547
  }
548
+ // A transition from an approved plan: a kind from the fixed list, under the same switch
549
+ if (allowed.motion && Object.hasOwn(TRANSITIONS, brief.transition ?? "")) {
550
+ clean.transition = brief.transition
551
+ if (brief.transitionAll === true) clean.transitionAll = true
552
+ }
553
+ // Motion graphics from an approved plan, only while the server's switch is on; each cleaned to the kit's shape
554
+ // TP9: a callout round a drawn box also, with editing.customMotion on
555
+ if (Array.isArray(brief.graphics) && brief.graphics.length && allowed.motion) clean.graphics = brief.graphics.slice(0, 12).map((g) => cleanGraphic(g, typeKitOn || (allowed.customMotion === true && g?.kind === "callout" && g?.mark) ? ALL_GRAPHIC_KINDS : GRAPHIC_KINDS)).filter(Boolean)
556
+ // TP7: a type kit or a style pack, from the person's brief or an approved plan, only with editing.typeKit on.
557
+ // The pack fills only what the brief leaves open; the kit is stored on the project by the make (EH-69)
558
+ if (typeKitOn && (brief.typeKit !== undefined || typeof brief.stylePack === "string")) {
559
+ let raw = brief.typeKit ?? null
560
+ if (typeof brief.stylePack === "string") {
561
+ if (!Object.hasOwn(STYLE_PACKS, brief.stylePack)) return refuse(res, 400, "There is no style pack by that name.")
562
+ const packed = applyStylePack(brief.stylePack, clean, { moods: allowed.craft ? ALL_MOODS : MOODS, grades: GRADES, transitions: TRANSITIONS, looks: ALL_LOOKS, motion: allowed.motion })
563
+ Object.assign(clean, packed.brief)
564
+ if (packed.notes.length) clean.packNotes = packed.notes
565
+ // The person's own pair, colours, logo and bar over the pack's
566
+ raw = { ...packed.kit, ...(raw && typeof raw === "object" ? raw : {}), pack: brief.stylePack }
567
+ }
568
+ const { kit, problem } = cleanTypeKit(raw, { packs: STYLE_PACKS })
569
+ if (problem) return refuse(res, 400, `That type kit can't be used: ${problem}.`)
570
+ if (kit) clean.typeKit = kit
571
+ }
572
+ // TP6: the style brief the person kept, only with editing.referenceIntent on: a reference's id and the trait ids
573
+ // they unticked. Nothing else of it comes from the browser: the Host builds the lines again from the measured numbers
574
+ if (allowed.referenceIntent === true && brief.styleBrief && safeId(brief.styleBrief.ref)) clean.styleBrief = { ref: brief.styleBrief.ref, off: cleanOff(brief.styleBrief.off) }
396
575
  // Animated scenes from an approved plan, only while the server's switch is on; the recipe checks each again against the speech
397
576
  if (Array.isArray(brief.scenes) && brief.scenes.length && (await projects.features()).visuals) {
398
577
  clean.scenes = brief.scenes.slice(0, 12).map(cleanScene).filter(Boolean)
399
578
  clean.sceneSound = brief.sceneSound !== false
400
579
  }
401
580
  }
581
+ // The film's order (TP2), only from this make's own brief and only with editing.assembly on: the storyboard
582
+ // the Studio sent, or an approved plan's. Checked as set_assembly checks it; one file with none is the reel
583
+ // it always was, and with the switch off the key is dropped (ET-ASM-REG-01, EH-63)
584
+ if (brief && typeof brief === "object" && brief.assembly !== undefined && (await projects.features()).assembly === true) {
585
+ const assembly = { version: 1, parts: Array.isArray(brief.assembly?.parts) ? brief.assembly.parts : [] }
586
+ const problems = assemblyProblems(assembly, { project: state.log.current, index: state.index })
587
+ if (problems.length) return refuse(res, 400, `That order can't be made: ${problems[0]}`)
588
+ if (isAssembly(assembly.parts)) clean.assembly = assembly
589
+ }
402
590
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
403
- return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
591
+ if (brief?.fresh === true) clean.fresh = true
592
+ // The last make's story, set here by the Host (never taken from the browser) so a replay of this job has it too
593
+ const story = projects.keptStory(state, clean)
594
+ if (story) clean.story = story
595
+ const approved = cleanPlan(plan)
596
+ return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean, ...(approved ? { plan: approved } : {}) }))
597
+ }
598
+ // Three openings to choose from (TP8, editing.directorLoop): started as a job, each film streamed by the job's own
599
+ // record. Off, neither route exists
600
+ if (parts[2] === "openings" && (await projects.features()).directorLoop === true) {
601
+ if (parts.length === 3 && method === "POST") {
602
+ const { asset, brief } = await readJson(req)
603
+ if (asset !== undefined && (typeof asset !== "string" || !state.log.current.assets.some((a) => a.id === asset && a.kind === "video"))) return refuse(res, 400, "Name the take.")
604
+ // Only the look of the openings comes from the browser, each value from its fixed list
605
+ const clean = {}
606
+ if (brief && typeof brief === "object") {
607
+ if (Object.hasOwn(FORMATS, brief.format)) clean.format = brief.format
608
+ if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
609
+ if (Object.hasOwn(GRADES, brief.grade)) clean.grade = brief.grade
610
+ }
611
+ return say(200, jobs.start(state, { kind: "openings", ...(asset ? { asset } : {}), brief: clean }))
612
+ }
613
+ if (parts.length === 5 && method === "GET") {
614
+ const file = /^\d{1,9}$/.test(parts[3]) && /^[0-2]$/.test(parts[4]) ? projects.openingFile(state, Number(parts[3]), Number(parts[4])) : null
615
+ if (!file) return refuse(res, 404, "That opening isn't there any more.")
616
+ return sendFile(req, res, file)
617
+ }
404
618
  }
405
619
  // The person fixes a word the recogniser misheard (UX_SPEC §5)
406
620
  if (parts[2] === "words" && parts.length === 4 && method === "POST") {
@@ -427,13 +641,40 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
427
641
  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" })
428
642
  return res.end(html)
429
643
  }
644
+ // One motion graphic on the Plan Card, as the render will draw it: its own sandboxed document, no network
645
+ if (parts[2] === "graphic-preview" && parts.length === 3 && method === "GET") {
646
+ if (!(await projects.features()).motion) return refuse(res, 404, "Motion graphics aren't on.")
647
+ let graphic = null
648
+ try {
649
+ graphic = JSON.parse(url.searchParams.get("graphic") ?? "null")
650
+ } catch {
651
+ return refuse(res, 400, "That isn't a graphic.")
652
+ }
653
+ const html = projects.graphicPreview(state, graphic, url.searchParams.get("format"), { typeKit: (await projects.features()).typeKit === true, drawn: (await projects.features()).customMotion === true })
654
+ 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" })
655
+ return res.end(html)
656
+ }
430
657
  // The Director's plan: proposed in words with its settings; nothing is made here
431
658
  if (parts[2] === "plan" && parts.length === 3 && method === "POST") {
432
- const { text, history, previous, choices } = await readJson(req)
659
+ const { text, history, previous, choices, mentions, mark: drawn } = await readJson(req)
433
660
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want, in up to 2,000 characters.")
661
+ const mark = (await projects.features()).customMotion === true ? cleanMark(drawn) : undefined
662
+ if (mark === null) return refuse(res, 400, "That drawing isn't a box, ring or arrow inside the frame. Draw it again.")
434
663
  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) })) : []
435
- 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
436
- return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {} }))
664
+ const prior = cleanPlan(previous)
665
+ return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {}, mentions, ...(mark ? { mark } : {}) }))
666
+ }
667
+ // TP6 (editing.referenceIntent): a reference's style is read as a job (progress, cancel) and its brief is built from
668
+ // what the job kept; asking for a brief never measures. Off, neither route exists
669
+ if (parts[2] === "references" && parts.length === 5 && (parts[4] === "measure" || parts[4] === "brief") && (await projects.features()).referenceIntent === true) {
670
+ const ref = decodeURIComponent(parts[3])
671
+ if (!state.log.current.assets.some((a) => a.id === ref && a.kind === "reference")) return refuse(res, 404, "There is no such reference in this project.")
672
+ if (parts[4] === "measure" && method === "POST") return say(200, jobs.start(state, { kind: "reference", asset: ref }))
673
+ if (parts[4] === "brief" && method === "GET") {
674
+ const format = url.searchParams.get("format")
675
+ const brief = await projects.styleBriefFor(state, ref, Object.hasOwn(FORMATS, format ?? "") ? format : undefined)
676
+ return say(200, brief ? { status: "ready", brief } : { status: "none" })
677
+ }
437
678
  }
438
679
  // A reference's classified analysis, measured once and kept
439
680
  if (parts[2] === "references" && parts.length === 4 && method === "GET") return say(200, await projects.referenceAnalysis(state, decodeURIComponent(parts[3])))
@@ -483,6 +724,9 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
483
724
  const url = new URL(req.url, "http://host")
484
725
  try {
485
726
  if (overSocket) {
727
+ // TP11: the channel's own secret on every command, so another account on a shared Windows computer
728
+ // (whose pipe Node can't make owner-only) gets nothing. A Host made without one (tests) is as before
729
+ if (ipcToken !== null && !sameSecret(req.headers[TOKEN_HEADER], ipcToken)) return refuse(res, 401, "This command didn't come from this account's Kriya.")
486
730
  if (url.pathname === "/internal/info") return json(res, 200, { pid, port: port(), stamp, busy: busy() })
487
731
  if (url.pathname === "/internal/launch" && req.method === "POST") {
488
732
  const token = mintToken((await readJson(req)).back)
@@ -16,6 +16,8 @@ import { encoderFor } from "../engine/capabilities.js"
16
16
  import { probe } from "../engine/probe.js"
17
17
  import { runTool } from "../engine/tool.js"
18
18
  import { editHome } from "./paths.js"
19
+ import { clipList, decideAssembly, resolveRefs } from "../director/assembly.js"
20
+ import { cleanLabel } from "../core/project.js"
19
21
 
20
22
  const VIDEO = new Set([".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi"])
21
23
  const REPORT_MS = 10_000 // At most this often (TOOLS_AND_CONTRACTS §5)
@@ -29,6 +31,8 @@ const FLICKS = 705_600_000
29
31
  const FILE_QUESTION_S = 600
30
32
  const TAKE_QUESTION_S = 300
31
33
  const TASTE_QUESTION_S = 3600
34
+ const ORDER_QUESTION_S = 600
35
+ const ORDER_OPTIONS = 4
32
36
  const TAKE_MARGIN = 0.1
33
37
  const CLIP_SECONDS = 5
34
38
  const WAIT_S = 25
@@ -82,6 +86,48 @@ export function secondsIn(brief) {
82
86
  return seconds >= 5 && seconds <= 600 ? seconds : undefined
83
87
  }
84
88
 
89
+ const SPINE = ["story", "whole"]
90
+ /** One order as the person reads it on a card: "Clip 2 (Intro), then clip 1". Numbers and their own labels, no file names. */
91
+ export function orderLine(assembly, project) {
92
+ const numbered = new Map(clipList(project).map((c) => [c.asset, c.n]))
93
+ const label = (asset) => cleanLabel(project.assets.find((a) => a.id === asset)?.label)
94
+ const line = assembly.parts
95
+ .filter((p) => SPINE.includes(p.use))
96
+ .map((p, i) => `${i ? "clip" : "Clip"} ${numbered.get(p.asset) ?? "?"}${label(p.asset) ? ` (${label(p.asset)})` : ""}`)
97
+ .join(", then ")
98
+ return line.length > 200 ? `${line.slice(0, 199)}…` : line
99
+ }
100
+
101
+ /**
102
+ * The order a Tavi brief names across the folder's clips (TP11), by code only: no model call, never the
103
+ * storyboard stored on the project (EH-63), only the project's own numbered clips (no reference, no path).
104
+ * @returns {Promise<{ assembly: object } | { options: { label: string, assembly: object }[] } | null>}
105
+ * null: the brief names no order (one file, or one clip), and the job is the reel it always was
106
+ */
107
+ export async function orderIn(brief, state) {
108
+ const project = state.log.current
109
+ const index = state.index ?? {}
110
+ const clips = clipList(project, index)
111
+ if (clips.filter((c) => c.picture && c.duration > 0).length < 2) return null
112
+ const said = resolveRefs(brief, clips, { index })
113
+ if (said.refs.length < 2) return null
114
+ const decided = await decideAssembly({ project, index, text: brief })
115
+ if (decided.assembly && !decided.open.length) return { assembly: decided.assembly }
116
+ // What code couldn't settle: each clip that fits the first open place, as its own order, for the person to pick
117
+ const open = decided.open.find((item) => item.candidates?.length >= 2)
118
+ if (!open) return null
119
+ const options = []
120
+ for (const asset of open.candidates.slice(0, ORDER_OPTIONS)) {
121
+ const n = clips.find((c) => c.asset === asset)?.n
122
+ // The place said ("the beach clip") becomes that clip's number, its own "clip" or "file" word with it
123
+ const place = new RegExp(`${open.said.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s+(?:clip|file|video|one))?`, "i")
124
+ const tried = await decideAssembly({ project, index, text: brief.replace(place, `clip ${n}`) })
125
+ if (tried.assembly && !tried.open.length && !options.some((o) => JSON.stringify(o.assembly.parts) === JSON.stringify(tried.assembly.parts))) options.push({ label: orderLine(tried.assembly, project), assembly: tried.assembly })
126
+ }
127
+ if (options.length === 1) return { assembly: options[0].assembly }
128
+ return options.length >= 2 ? { options } : null
129
+ }
130
+
85
131
  /**
86
132
  * A file small enough to upload: the master when it fits, else a lower bitrate that
87
133
  * does. @returns {Promise<string | null>} null when even that won't fit
@@ -310,6 +356,37 @@ export function createTavi({ home, projects, taste = projects.taste, jobs, tools
310
356
  }
311
357
  // Only this recipe reaches a make job so far (ED11, ED12)
312
358
  if (recipe && recipe !== "reel-talking-head") return refuse("not_allowed")
359
+ // TP11: an order across the folder's clips, only with editing.assembly on and Kriya's taviOrder (rule 17);
360
+ // otherwise, and for a brief that names one file, everything below is as it was (ET-TP-REG-04)
361
+ const ordered = (state, assembly) => {
362
+ const seconds = secondsIn(brief)
363
+ const started = jobs().start(state, { kind: "make", brief: { effort, ...(seconds && { targetDuration: seconds * FLICKS }), assembly }, dispatch, dispatchJob: job })
364
+ entry.hostJob = started.id
365
+ return { accepted: true }
366
+ }
367
+ try {
368
+ const features = revisionOf ? null : await projects.features?.().catch(() => null)
369
+ const known = features?.assembly === true && features?.taviOrder === true ? projects.list().find((p) => dirname(p.file) === folder) : null
370
+ if (known) {
371
+ const state = await projects.get(known.id)
372
+ const order = await orderIn(brief, state)
373
+ if (order?.assembly) return ordered(state, order.assembly)
374
+ if (order?.options) {
375
+ void askPerson(dispatch, entry, job, {
376
+ kind: "order",
377
+ prompt: "Which order did you mean?",
378
+ options: order.options.map((o) => ({ label: o.label })),
379
+ defaultOption: 0,
380
+ timeoutSeconds: ORDER_QUESTION_S,
381
+ })
382
+ .then((option) => (entry.abort.signal.aborted ? final(dispatch, "canceled", { code: "canceled" }) : ordered(state, order.options[option].assembly)))
383
+ .catch((error) => (entry.abort.signal.aborted ? final(dispatch, "canceled", { code: "canceled" }) : failed(error)))
384
+ return { accepted: true }
385
+ }
386
+ }
387
+ } catch (error) {
388
+ return failed(error)
389
+ }
313
390
  try {
314
391
  const files = rankFiles(folder, brief)
315
392
  if (!files.length && !revisionOf) return await refuse("no_media")
@@ -8,9 +8,11 @@
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 { remapIds, remapOp, replayable } from "../director/continuity.js"
11
12
  import { planReel, recipeFor } from "../recipes/reel.js"
12
13
  import { search } from "./loop.js"
13
14
  import { repairLadder } from "./repair.js"
15
+ import { roundsLeft, watchAndFix } from "../director/watch-fix.js"
14
16
 
15
17
  const FLICKS = 705_600_000
16
18
  const TEXT_GATES = new Set(["QG-08", "QG-09", "QG-10", "QG-11"])
@@ -37,14 +39,23 @@ export function planVerdict(project, index, recipe, { engineVersion = "f0", runt
37
39
  * ask: Function, render: (project: object, deliverable: string, signal?: AbortSignal) => Promise<{ file: string, plan: object }>,
38
40
  * sourcePath: (asset: string) => string, signal?: AbortSignal, onStage?: (stage: string) => void, run?: Function,
39
41
  * gateKit?: { tilePath?: Function, motion?: object, work?: string }, the Engine's tiles and Chrome, for QG-08 and QG-09
42
+ * watch?: { view: (attempt: object) => Promise<{ report: object, timeline: object }> } | null, the Director's watch-and-fix (TP8, editing.directorLoop); absent, the make as before
43
+ * onLive?: (event: object) => void, the make's real state as it happens (editing.livePreview): each planned candidate, each render, gate results, repairs and watch rounds. Never written to history; a throw here is ignored
40
44
  * }} input
41
45
  */
42
- export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null }) {
46
+ export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null, edits = [], watch = null, onLive = null }) {
47
+ // edits: what the person did to the last cut, replayed on each candidate before it is rendered and gated
43
48
  // planner: a recipe with no variants to try (a programme, a montage), instead of the reel
44
49
  const recipe = plannerRecipe ?? recipeFor(brief)
45
50
  let calls = 0
46
51
  const notes = []
47
52
  const slots = {}
53
+ const live = (event) => {
54
+ if (!onLive) return
55
+ try {
56
+ onLive(event)
57
+ } catch {}
58
+ }
48
59
 
49
60
  const variantOf = async (variant) => {
50
61
  onStage("story")
@@ -52,7 +63,9 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
52
63
  calls += made.calls
53
64
  Object.assign(slots, made.slots)
54
65
  for (const note of made.notes) if (!notes.includes(note)) notes.push(note)
55
- return { ...made, variant }
66
+ const candidate = { ...carryEdits(made, edits, { before: project, index }), variant }
67
+ live({ stage: "plan", before: project, ops: candidate.ops, round: variant.tighter ? 2 : variant.noHook ? 3 : 1 })
68
+ return candidate
56
69
  }
57
70
 
58
71
  const evaluate = async (candidate) => {
@@ -62,17 +75,31 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
62
75
  onStage("check")
63
76
  const deliverable = candidate.project.deliverables.find((d) => d.preset === recipe.deliverable.preset)
64
77
  const check = (file, plan, project) => runGates({ file, plan, project, index, sourcePath, thresholds: recipe.thresholds, ...gateKit, ...(run ? { run } : {}) })
78
+ live({ stage: "render", project: candidate.project })
65
79
  const { file, plan } = await render(candidate.project, deliverable.id, signal)
66
80
  let attempt = { project: candidate.project, ops: candidate.ops, file, plan, checked: await check(file, plan, candidate.project) }
81
+ live({ stage: "check", gates: attempt.checked.gates })
67
82
  // The repair ladder (QUALITY_GATES §4): code's fixes first, never a looser threshold, never a must-keep cut
68
83
  if (attempt.checked.blocking > 0 || attempt.checked.briefMisses > 0) {
69
84
  onStage("repair")
70
85
  const mustKeeps = (project) => planVerdict({ ...project, brief: { ...project.brief, targetDuration: undefined } }, index, recipe).briefMisses === 0
71
- const ladder = await repairLadder(attempt, { index, render: (project) => render(project, deliverable.id, signal), check, keepsMustKeeps: mustKeeps, signal })
86
+ const ladder = await repairLadder(attempt, { index, render: (project) => (live({ stage: "render", repair: true, project }), render(project, deliverable.id, signal)), check, keepsMustKeeps: mustKeeps, signal })
72
87
  attempt = ladder.best
88
+ live({ stage: "repair", attempts: ladder.attempts, project: attempt.project })
89
+ live({ stage: "check", gates: attempt.checked.gates })
73
90
  candidate.repairs = ladder.attempts
74
91
  candidate.person = ladder.person
75
92
  }
93
+ // TP8: the Director watches what was rendered and fixes it, in the rounds the ladder left (EH-74)
94
+ const left = watch ? roundsLeft(candidate.repairs) : 0
95
+ if (left > 0) {
96
+ onStage("watch")
97
+ const watched = await watchAndFix(attempt, { index, view: watch.view, render: (project) => render(project, deliverable.id, signal), check, rounds: left, signal })
98
+ attempt = watched.best
99
+ live({ stage: "watch", rounds: watched.rounds, project: attempt.project })
100
+ live({ stage: "check", gates: attempt.checked.gates })
101
+ candidate.watched = { rounds: watched.rounds, left: watched.left, score: watched.best.report?.score ?? null }
102
+ }
76
103
  Object.assign(candidate, { project: attempt.project, ops: attempt.ops, file: attempt.file, plan: attempt.plan, gates: attempt.checked })
77
104
  const checked = attempt.checked
78
105
  return { level: "F5", blocking: checked.blocking, briefMisses: checked.briefMisses, notes: checked.notes, quality: f0.quality, verdict: checked.verdict, failed: checked.gates?.filter((g) => g.status === "failed" && g.severity !== "note").map((g) => g.id) ?? [] }
@@ -94,6 +121,20 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
94
121
  return { best: best.start ? null : best, outcome, notes, calls, slots, head }
95
122
  }
96
123
 
124
+ /**
125
+ * The person's edits since the last make, replayed on a remade cut: each pointed at the clip
126
+ * that replaced its own, applied if it still fits and listed if it doesn't, never forced.
127
+ * @returns the candidate with those operations after its own, and `dropped`
128
+ */
129
+ export function carryEdits(made, edits, { before, index }) {
130
+ const worth = replayable(edits, before)
131
+ if (!worth.length) return made
132
+ const ids = remapIds(before, made.project, index)
133
+ const { ops, dropped } = rebase(made.project, worth.map((op) => remapOp(op, ids)), index)
134
+ const landed = ops.length ? apply(made.project, ops, { index, author: "agent" }) : null
135
+ return { ...made, ops: [...made.ops, ...ops], project: landed?.applied ? landed.project : made.project, carried: landed?.applied ? ops : [], dropped }
136
+ }
137
+
97
138
  /**
98
139
  * Lands the winner on HEAD. Unchanged HEAD: one entry. Changed: each operation is tried
99
140
  * on the new HEAD, and one that conflicts is dropped and listed, never forced.