@kriya-ai/harness 0.2.5 → 2.0.1

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 +60 -5
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +498 -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 +381 -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 +436 -0
  33. package/plugins/runstrip/index.js +312 -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 +65 -6
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +169 -2
  44. package/src/edit/core/plan.js +65 -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/type-kit.js +173 -0
  51. package/src/edit/director/ask.js +37 -3
  52. package/src/edit/director/assembly.js +829 -0
  53. package/src/edit/director/continuity.js +9 -1
  54. package/src/edit/director/custom-motion.js +88 -0
  55. package/src/edit/director/graphics.js +44 -10
  56. package/src/edit/director/intent.js +125 -0
  57. package/src/edit/director/mentions.js +52 -0
  58. package/src/edit/director/plan.js +43 -11
  59. package/src/edit/director/revise.js +132 -9
  60. package/src/edit/director/viewer.js +136 -0
  61. package/src/edit/director/watch-fix.js +119 -0
  62. package/src/edit/engine/captions.js +110 -5
  63. package/src/edit/engine/confine.js +81 -4
  64. package/src/edit/engine/custom.js +243 -0
  65. package/src/edit/engine/dna2.js +893 -0
  66. package/src/edit/engine/fonts.js +218 -0
  67. package/src/edit/engine/graphics.js +271 -10
  68. package/src/edit/engine/index.js +14 -5
  69. package/src/edit/engine/motion.js +148 -13
  70. package/src/edit/engine/music-bed.js +59 -1
  71. package/src/edit/engine/packs.js +11 -0
  72. package/src/edit/engine/reference2.js +26 -0
  73. package/src/edit/engine/sfx.js +56 -1
  74. package/src/edit/engine/tool.js +21 -5
  75. package/src/edit/gates/assembly.js +194 -0
  76. package/src/edit/gates/copy.js +7 -4
  77. package/src/edit/gates/index.js +72 -7
  78. package/src/edit/gates/reference.js +115 -0
  79. package/src/edit/gates/tile.js +96 -0
  80. package/src/edit/host/client.js +8 -3
  81. package/src/edit/host/clips.js +33 -0
  82. package/src/edit/host/jobs.js +9 -3
  83. package/src/edit/host/layers.js +134 -0
  84. package/src/edit/host/main.js +10 -3
  85. package/src/edit/host/paths.js +21 -3
  86. package/src/edit/host/preview.js +108 -0
  87. package/src/edit/host/projects.js +443 -34
  88. package/src/edit/host/server.js +235 -20
  89. package/src/edit/host/tavi.js +77 -0
  90. package/src/edit/index/index.js +3 -2
  91. package/src/edit/loop/make.js +28 -3
  92. package/src/edit/recipes/assembly.js +352 -0
  93. package/src/edit/recipes/graphic-clips.js +4 -2
  94. package/src/edit/recipes/openings.js +36 -0
  95. package/src/edit/recipes/reel.js +104 -14
  96. package/src/edit/recipes/reference-look.js +29 -0
  97. package/src/edit/recipes/short-from-long.js +3 -3
  98. package/src/edit/recipes/sound.js +71 -0
  99. package/src/edit/runtime/cli.js +26 -5
  100. package/src/edit/runtime/fetch.js +4 -4
  101. package/src/edit/runtime/licences.js +7 -1
  102. package/src/explore.js +103 -0
  103. package/src/failure.js +1 -1
  104. package/src/gate-commands.js +114 -0
  105. package/src/gates/api.js +127 -0
  106. package/src/gates/commands.js +111 -0
  107. package/src/gates/detectors.js +370 -0
  108. package/src/gates/http.js +62 -0
  109. package/src/gates/index.js +196 -0
  110. package/src/gates/page.js +264 -0
  111. package/src/gates/sast.js +64 -0
  112. package/src/gates/stack.js +110 -0
  113. package/src/gates/tenant.js +162 -0
  114. package/src/gates/three.js +431 -0
  115. package/src/gates/ui.js +111 -0
  116. package/src/gateway-proxy.js +20 -2
  117. package/src/launch.js +39 -5
  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 +67 -0
  122. package/src/orchestra.js +50 -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 +449 -1
  134. package/studio/dist/studio.js +3 -3
@@ -9,9 +9,11 @@ import { join } from "node:path"
9
9
 
10
10
  import { childEnv } from "../runtime/setup.js"
11
11
  import { confine, confinement, installOf } from "./confine.js"
12
+ import { installedFonts, withFonts } from "./fonts.js"
12
13
  import { buildScene, SCENE_VERSION } from "./scenes.js"
13
14
  import { buildGraphic, GRAPHIC_VERSION } from "./graphics.js"
14
15
  import { EngineFailure, runTool } from "./tool.js"
16
+ import { CUSTOM_BLOCK, CUSTOM_VERSION, partsProblems } from "./custom.js"
15
17
 
16
18
  const FLICKS = 705_600_000
17
19
 
@@ -70,15 +72,19 @@ export function tileSeconds(flicks, fps) {
70
72
  * fit.box: the element measured against the box, when it isn't the one whose font shrinks (a plate around the text)
71
73
  */
72
74
  export function tileDocument({ width, height, duration, css, body, animations, fit }) {
75
+ // TP7: a tile with shipped fonts fits and starts once they are in, and says so (data-ready); one without is the document it was
76
+ const fonts = css.includes("kriya-font:")
73
77
  const fitting = fit ? `{const t=document.getElementById(${scriptJson(fit.id)}),a=document.getElementById(${scriptJson(fit.within)}),b=document.getElementById(${scriptJson(fit.box ?? fit.id)});let s=parseFloat(getComputedStyle(t).fontSize);while((b.offsetHeight>a.clientHeight||b.scrollWidth>a.clientWidth)&&s>${Number(fit.min)}){s-=1;t.style.fontSize=s+"px"}}` : ""
74
78
  const seconds = (duration / FLICKS).toFixed(6)
75
79
  return [
76
80
  "<!doctype html>",
77
- `<html><head><meta charset="utf-8">${CSP_META}`,
81
+ `<html${fonts ? " data-fonts" : ""}><head><meta charset="utf-8">${CSP_META}`,
78
82
  `<style>html,body{margin:0;background:transparent;overflow:hidden}#stage{position:relative;width:${width}px;height:${height}px;overflow:hidden}${css}</style></head>`,
79
83
  `<body><div id="stage" data-composition-id="kriya" data-no-timeline data-start="0" data-duration="${seconds}" data-width="${width}" data-height="${height}">`,
80
84
  `<div id="clip" class="clip" data-start="0" data-duration="${seconds}" data-track-index="0">${body}</div></div>`,
81
- `<script>${fitting}for (const a of ${scriptJson(animations)}) document.getElementById(a.id).animate(a.keyframes, a.options)</script>`,
85
+ fonts
86
+ ? `<script>Promise.all([...document.fonts].map((f)=>f.load().catch(()=>null))).then(()=>{${fitting}for (const a of ${scriptJson(animations)}) document.getElementById(a.id).animate(a.keyframes, a.options);document.documentElement.dataset.ready="1"})</script>`
87
+ : `<script>${fitting}for (const a of ${scriptJson(animations)}) document.getElementById(a.id).animate(a.keyframes, a.options)</script>`,
82
88
  "</body></html>",
83
89
  ].join("")
84
90
  }
@@ -150,7 +156,7 @@ export function blockComposition(node, { output, canvas }) {
150
156
  const box = node.placement ?? { x: Math.round(canvas.width * 0.1), y: Math.round(canvas.height * 0.4), w: Math.round(canvas.width * 0.8), h: Math.round(canvas.height * 0.12) }
151
157
  const area = { x: Math.round(box.x * sx), y: Math.round(box.y * sy), w: Math.round(box.w * sx), h: Math.round(box.h * sy) }
152
158
  const size = Math.round(output.height * 0.03)
153
- return tileDocument({ width: output.width, height: output.height, duration: node.duration, ...block.build({ variables: node.variables, area, size, output, duration: node.duration }) })
159
+ return tileDocument({ width: output.width, height: output.height, duration: node.duration, ...block.build({ variables: node.variables, area, size, output, duration: node.duration, ...(node.type ? { type: node.type } : {}) }) })
154
160
  }
155
161
 
156
162
  /* ─────────────────────────────── model-written code ─────────────────────────────── */
@@ -190,9 +196,29 @@ export function customComposition(html, { allowed, which = confinement() }) {
190
196
  return `${html.slice(0, head.index + head[0].length)}${CSP_META}${html.slice(head.index + head[0].length)}`
191
197
  }
192
198
 
193
- /** The composition for any tile in a plan. */
199
+ /**
200
+ * A custom block's tile (MG2, TP9): the stored parts checked again (a project is read back from disk),
201
+ * set in Kriya's own document at the canvas's size and scaled to the output, passed through
202
+ * customComposition (the lint over the whole document; Kriya's CSP first), and only then each slot
203
+ * filled with its words, escaped. Words go in last so a word the speaker said ("fetch", "Date") is never
204
+ * read as code, and can never be code: escaped text has no markup.
205
+ * @param {{ allowed: boolean, which?: ReturnType<typeof confinement> }} gate allowed: editing.customMotion
206
+ */
207
+ export function customDocument(node, { output, canvas }, gate) {
208
+ if (node.blockId !== CUSTOM_BLOCK || node.version !== CUSTOM_VERSION) throw new EngineFailure("plan", "unknown_block", `There is no motion block "${node.blockId}" version ${node.version}.`)
209
+ const checked = partsProblems(node.variables)
210
+ if (checked.problems.length) throw new EngineFailure("plan", "bad_composition", `This custom animation was refused: ${checked.problems[0]}.`)
211
+ const sx = (output.width / canvas.width).toFixed(6)
212
+ const sy = (output.height / canvas.height).toFixed(6)
213
+ const css = `#mg{position:absolute;left:0;top:0;width:${canvas.width}px;height:${canvas.height}px;transform:scale(${sx},${sy});transform-origin:0 0;overflow:hidden}${node.variables.css}`
214
+ const html = customComposition(tileDocument({ width: output.width, height: output.height, duration: node.duration, css, body: `<div id="mg">${checked.parsed.html}</div>`, animations: node.variables.animations }), gate)
215
+ return html.replace(/⟦(\d)⟧/g, (_, i) => escapeText(checked.texts[Number(i)]))
216
+ }
217
+
218
+ /** The composition for any tile in a plan. A custom tile is in a plan only when editing.customMotion was on at compile. */
194
219
  export function compositionFor(tile, frame, captions) {
195
220
  if (tile.kind === "caption") return captions(tile.node, frame)
221
+ if (tile.kind === "block" && tile.node.blockId === CUSTOM_BLOCK) return customDocument(tile.node, frame, { allowed: true })
196
222
  if (tile.kind === "block") return blockComposition(tile.node, frame)
197
223
  throw new EngineFailure("plan", "unknown_tile", `This render can't draw a ${tile.kind} tile.`)
198
224
  }
@@ -214,9 +240,11 @@ export function motionRuntime(runtime, platform = `${process.platform}-${process
214
240
  const chromePath = chrome ? join(runtime.dir, chrome.id, chrome.entry) : null
215
241
  if (!chromePath || !existsSync(chromePath)) return { missing: "This Media Runtime has no Chrome for the motion layer." }
216
242
  // Without HyperFrames, Kriya draws tiles in the runtime's own Chrome, frame by frame (renderTileInChrome)
217
- if (!existsSync(cli)) return { cli: null, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, chrome.id))] }
243
+ // TP7: the pack's fonts, put into each tile as data by the renderer; none installed is an empty map
244
+ const fonts = installedFonts(runtime, platform)
245
+ if (!existsSync(cli)) return { cli: null, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, chrome.id))], fonts }
218
246
  // The runtime's own folders, after links: all a confined render may read of it
219
- return { cli, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, "hyperframes")), realpathSync(join(runtime.dir, chrome.id))] }
247
+ return { cli, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, "hyperframes")), realpathSync(join(runtime.dir, chrome.id))], fonts }
220
248
  }
221
249
 
222
250
  /** The environment for a confined render: built from scratch, telemetry off (EH-43), home in the work folder. */
@@ -235,7 +263,7 @@ export async function renderTile({ html, work, output, fps, runtime, run = runTo
235
263
  const comp = join(work, "comp")
236
264
  mkdirSync(join(work, "tmp"), { recursive: true })
237
265
  mkdirSync(comp, { recursive: true })
238
- writeFileSync(join(comp, "index.html"), html)
266
+ writeFileSync(join(comp, "index.html"), withFonts(html, runtime.fonts))
239
267
  const outDir = output.slice(0, output.lastIndexOf("/"))
240
268
  const args = [runtime.cli, "render", comp, "--format", "mov", "--prores-profile", "4444", "--fps", `${fps.n}/${fps.d}`, "--workers", "1", "--quiet", "--no-wait", "--no-browser-gpu", "-o", output]
241
269
  const { command, args: wrapped } = confine(process.execPath, args, { read: [installOf(process.execPath), ...runtime.reads, ...ffmpegHome()], write: [work, outDir] }, which)
@@ -254,8 +282,9 @@ export async function renderTileInChrome({ html, work, output, fps, runtime, run
254
282
  const dir = join(work, "frames")
255
283
  mkdirSync(dir, { recursive: true })
256
284
  await withChrome({ work, runtime, which, launch }, async (page) => {
257
- writeFileSync(join(work, "index.html"), html)
285
+ writeFileSync(join(work, "index.html"), withFonts(html, runtime.fonts))
258
286
  await page.goto(`file://${join(work, "index.html")}`)
287
+ await fontsIn(page)
259
288
  const [width, height] = await page.evaluate(() => {
260
289
  const stage = document.getElementById("stage")
261
290
  return [Number(stage.dataset.width), Number(stage.dataset.height)]
@@ -277,6 +306,9 @@ export async function renderTileInChrome({ html, work, output, fps, runtime, run
277
306
  if (!existsSync(output)) throw new EngineFailure("render", "failed", "The caption renderer finished without writing its tile.")
278
307
  }
279
308
 
309
+ // A tile with shipped fonts starts its animations once they are in (tileDocument); one without is ready at load
310
+ const fontsIn = (page) => page.waitForFunction(() => !document.documentElement.hasAttribute("data-fonts") || document.documentElement.hasAttribute("data-ready"), null, { timeout: 30_000 })
311
+
280
312
  /** The runtime's Chrome, started confined by playwright through a sandbox wrapper; one page. */
281
313
  async function withChrome({ work, runtime, which, launch }, use) {
282
314
  const { chromium } = launch ? {} : await import("playwright-core")
@@ -284,10 +316,22 @@ async function withChrome({ work, runtime, which, launch }, use) {
284
316
  if ([work, runtime.chrome].some((path) => path.includes("'"))) throw new EngineFailure("environment", "bad_path", "A folder name with a quote can't hold the motion layer's work.")
285
317
  mkdirSync(join(work, "tmp"), { recursive: true })
286
318
  // Playwright starts this script; the script starts Chrome inside the sandbox
287
- const { args } = confine(runtime.chrome, [], { read: [...runtime.reads, work], write: [work] }, which)
288
- writeFileSync(join(work, "chrome.sb"), args[1])
289
- const wrapper = join(work, "chrome.sh")
290
- writeFileSync(wrapper, `#!/bin/sh\nexec /usr/bin/sandbox-exec -f '${join(work, "chrome.sb")}' '${runtime.chrome}' "$@"\n`, { mode: 0o755 })
319
+ const confined = confine(runtime.chrome, [], { read: [...runtime.reads, work], write: [work] }, which)
320
+ let wrapper
321
+ if (which.kind === "sandbox-exec") {
322
+ writeFileSync(join(work, "chrome.sb"), confined.args[1])
323
+ wrapper = join(work, "chrome.sh")
324
+ writeFileSync(wrapper, `#!/bin/sh\nexec /usr/bin/sandbox-exec -f '${join(work, "chrome.sb")}' '${runtime.chrome}' "$@"\n`, { mode: 0o755 })
325
+ } else if (which.kind === "appcontainer") {
326
+ // TP11 seam: the Windows runner, as a batch file Playwright can start (paths are plain: confine.js checked them)
327
+ wrapper = join(work, "chrome.cmd")
328
+ writeFileSync(wrapper, `@echo off\r\n${[confined.command, ...confined.args].map((a) => `"${a}"`).join(" ")} %*\r\n`)
329
+ } else {
330
+ // TP11: bubblewrap on Linux, every argument quoted for the shell
331
+ wrapper = join(work, "chrome.sh")
332
+ const quote = (a) => `'${String(a).replace(/'/g, "'\\''")}'`
333
+ writeFileSync(wrapper, `#!/bin/sh\nexec ${[confined.command, ...confined.args].map(quote).join(" ")} "$@"\n`, { mode: 0o755 })
334
+ }
291
335
  const context = await open(join(work, "profile"), { executablePath: wrapper, headless: true, offline: true, env: { HOME: work, TMPDIR: join(work, "tmp") } })
292
336
  try {
293
337
  return await use(context.pages()[0] ?? (await context.newPage()))
@@ -331,15 +375,106 @@ export async function measureText({ items, work, runtime, which = confinement(),
331
375
  const files = items.map((item, i) => {
332
376
  const dir = join(work, `c${i}`)
333
377
  mkdirSync(dir, { recursive: true })
334
- writeFileSync(join(dir, "index.html"), item.html)
378
+ writeFileSync(join(dir, "index.html"), withFonts(item.html, runtime.fonts))
335
379
  return join(dir, "index.html")
336
380
  })
337
381
  return withChrome({ work, runtime, which, launch }, async (page) => {
338
382
  const out = new Map()
339
383
  for (const [i, item] of items.entries()) {
340
384
  await page.goto(`file://${files[i]}`)
385
+ await fontsIn(page)
341
386
  out.set(item.id, await page.evaluate(readBoxes, item.times))
342
387
  }
343
388
  return out
344
389
  })
345
390
  }
391
+
392
+ // Run in the page by Kriya: each text element's drawn clusters (a range per grapheme with a box of its own),
393
+ // and its missing ones: a cluster drawn on a canvas in its own font the same, pixel for pixel, as a
394
+ // noncharacter (U+FDD0, which no font maps) is the font's empty box, however the stack fell back
395
+ function readClusters() {
396
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" })
397
+ const canvas = document.createElement("canvas")
398
+ const ctx = canvas.getContext("2d", { willReadFrequently: true })
399
+ const pixels = (text, font, px) => {
400
+ canvas.width = Math.ceil(px * 4)
401
+ canvas.height = Math.ceil(px * 2)
402
+ ctx.font = font
403
+ ctx.textBaseline = "middle"
404
+ ctx.fillStyle = "#000"
405
+ ctx.clearRect(0, 0, canvas.width, canvas.height)
406
+ ctx.fillText(text, px * 0.5, px)
407
+ return ctx.getImageData(0, 0, canvas.width, canvas.height).data
408
+ }
409
+ const same = (a, b) => a.length === b.length && a.every((v, i) => v === b[i])
410
+ return [...document.querySelectorAll("[data-text]")].map((el) => {
411
+ let drawn = 0
412
+ let missing = 0
413
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT)
414
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
415
+ const style = getComputedStyle(node.parentElement)
416
+ const px = parseFloat(style.fontSize)
417
+ const font = `${style.fontStyle} ${style.fontWeight} ${px}px ${style.fontFamily}`
418
+ const empty = pixels("\uFDD0", font, px)
419
+ for (const { segment, index } of segmenter.segment(node.data)) {
420
+ if (!/\S/u.test(segment)) continue
421
+ const range = document.createRange()
422
+ range.setStart(node, index)
423
+ range.setEnd(node, index + segment.length)
424
+ const box = range.getBoundingClientRect()
425
+ if (box.width > 0 && box.height > 0) drawn++
426
+ if (same(pixels(segment, font, px), empty)) missing++
427
+ }
428
+ }
429
+ return { text: el.textContent, drawn, missing }
430
+ })
431
+ }
432
+
433
+ /**
434
+ * QG-10's check for scripts no reader reads (TP7, CRAFT §5.1): each composition at rest in
435
+ * the runtime's Chrome, inside the sandbox, and per text element the fonts Chrome drew its
436
+ * glyphs with (DevTools' platform fonts) and the clusters it drew.
437
+ * @param {{ items: { id: string, html: string, at: number }[], work: string, runtime: object, which?: object, launch?: Function }} input at: ms
438
+ * @returns {Promise<Map<string, { text: string, drawn: number, fonts: { family: string, custom: boolean, glyphs: number }[] }[]>>}
439
+ */
440
+ export async function checkGlyphs({ items, work, runtime, which = confinement(), launch }) {
441
+ if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
442
+ mkdirSync(join(work, "tmp"), { recursive: true })
443
+ return withChrome({ work, runtime, which, launch }, async (page) => {
444
+ const cdp = await page.context().newCDPSession(page)
445
+ await cdp.send("DOM.enable")
446
+ await cdp.send("CSS.enable")
447
+ const out = new Map()
448
+ for (const [i, item] of items.entries()) {
449
+ const file = join(work, `g${i}.html`)
450
+ writeFileSync(file, withFonts(item.html, runtime.fonts))
451
+ await page.goto(`file://${file}`)
452
+ await fontsIn(page)
453
+ await page.evaluate((t) => {
454
+ for (const animation of document.getAnimations()) {
455
+ animation.pause()
456
+ animation.currentTime = t
457
+ }
458
+ }, item.at)
459
+ const clusters = await page.evaluate(readClusters)
460
+ const { root } = await cdp.send("DOM.getDocument", { depth: -1 })
461
+ const { nodeIds } = await cdp.send("DOM.querySelectorAll", { nodeId: root.nodeId, selector: "[data-text]" })
462
+ const fonts = []
463
+ // A node reports only its own text children, and a caption's words sit in spans: the element and all inside it
464
+ for (const nodeId of nodeIds) {
465
+ const inside = (await cdp.send("DOM.querySelectorAll", { nodeId, selector: "*" })).nodeIds
466
+ const used = new Map()
467
+ for (const id of [nodeId, ...inside]) {
468
+ for (const f of (await cdp.send("CSS.getPlatformFontsForNode", { nodeId: id })).fonts) {
469
+ const seen = used.get(f.familyName) ?? { family: f.familyName, custom: f.isCustomFont, glyphs: 0 }
470
+ seen.glyphs += f.glyphCount
471
+ used.set(f.familyName, seen)
472
+ }
473
+ }
474
+ fonts.push([...used.values()])
475
+ }
476
+ out.set(item.id, clusters.map((c, k) => ({ ...c, fonts: fonts[k] ?? [] })))
477
+ }
478
+ return out
479
+ })
480
+ }
@@ -14,6 +14,19 @@ export const MOODS = {
14
14
  warm: { bpm: 92, chords: [[48, 52, 55, 59], [45, 48, 52, 55], [53, 57, 60, 64], [55, 59, 62, 65]], kick: 0.3, hat: 0.06, pulse: 0.25 },
15
15
  }
16
16
 
17
+ // TP10 (CRAFT_UPGRADE §8, EDD-69): seven more moods, still data, still written by code. Their own table,
18
+ // offered only with editing.craft on, so the plan's schema and the Studio's choices are what they were without it
19
+ export const MORE_MOODS = {
20
+ bright: { bpm: 120, chords: [[60, 64, 67], [55, 59, 62], [57, 60, 64], [53, 57, 60]], kick: 0.5, hat: 0.14, pulse: 0.3 },
21
+ tense: { bpm: 96, chords: [[57, 60, 63], [57, 60, 64], [53, 56, 60], [52, 55, 59]], kick: 0.4, hat: 0.05, pulse: 0.5 },
22
+ dreamy: { bpm: 70, chords: [[52, 55, 59, 62], [48, 52, 55, 59], [53, 57, 60, 64], [50, 53, 57, 60]], kick: 0, hat: 0.03, pulse: 0.1 },
23
+ driving: { bpm: 128, chords: [[50, 53, 57], [46, 50, 53], [48, 52, 55], [45, 48, 52]], kick: 0.65, hat: 0.1, pulse: 0.45 },
24
+ playful: { bpm: 108, chords: [[60, 64, 67], [62, 65, 69], [64, 67, 71], [65, 69, 72]], kick: 0.35, hat: 0.1, pulse: 0.3 },
25
+ epic: { bpm: 84, chords: [[45, 52, 57], [41, 48, 53], [48, 55, 60], [43, 50, 55]], kick: 0.6, hat: 0, pulse: 0.2 },
26
+ lofi: { bpm: 76, chords: [[50, 53, 57, 60], [55, 59, 62, 65], [48, 52, 55, 59], [45, 48, 52, 55]], kick: 0.45, hat: 0.08, pulse: 0.2 },
27
+ }
28
+ export const ALL_MOODS = { ...MOODS, ...MORE_MOODS }
29
+
17
30
  const hz = (note) => 440 * 2 ** ((note - 69) / 12)
18
31
 
19
32
  /**
@@ -22,7 +35,7 @@ const hz = (note) => 440 * 2 ** ((note - 69) / 12)
22
35
  */
23
36
  export function writeMusicBed(file, { mood = "calm", seconds = 60, bpm } = {}) {
24
37
  // A music reference's tempo can set the bed's (classified by analyseReference)
25
- const spec = { ...(MOODS[mood] ?? MOODS.calm), ...(bpm >= 60 && bpm <= 180 ? { bpm: Math.round(bpm) } : {}) }
38
+ const spec = { ...(ALL_MOODS[mood] ?? MOODS.calm), ...(bpm >= 60 && bpm <= 180 ? { bpm: Math.round(bpm) } : {}) }
26
39
  const total = Math.ceil((Math.max(5, seconds) + 2) * RATE)
27
40
  const beat = (60 / spec.bpm) * RATE // samples a beat
28
41
  const bar = beat * 4
@@ -82,6 +95,51 @@ export function writeMusicBed(file, { mood = "calm", seconds = 60, bpm } = {}) {
82
95
  return { file, seconds: total / RATE, bpm: spec.bpm }
83
96
  }
84
97
 
98
+ /**
99
+ * An accent in a mood's own key (TP10): the bed's first chord struck once over a soft low thump, for a
100
+ * make to land on the cut's joins. Its peak is measured from its samples, as the sounds' are, and silence
101
+ * is put before it so the peak falls on a whole frame of `fps`: the timeline places a sound on frames, so
102
+ * a peak between frames would land up to a frame early (found by TP10's exit test: 37 ms on one mood).
103
+ * @returns {{ file: string, peak: number }} peak in seconds from the file's start
104
+ */
105
+ export function writeAccent(file, mood = "calm", { fps = { n: 30, d: 1 } } = {}) {
106
+ const spec = ALL_MOODS[mood] ?? MOODS.calm
107
+ const total = Math.round(1.2 * RATE)
108
+ const left = new Float32Array(total)
109
+ const right = new Float32Array(total)
110
+ for (let i = 0; i < total; i++) {
111
+ const t = i / RATE
112
+ const attack = Math.min(1, t * 100) // 10 ms: struck, but no click at the cut it lands on (QG-05)
113
+ let v = 0
114
+ for (const note of spec.chords[0]) v += Math.sin(2 * Math.PI * hz(note) * t) + 0.3 * Math.sin(2 * Math.PI * hz(note) * 2 * t)
115
+ // The chord rings under a struck thump: the thump is the clear loudest moment, so the hit means one instant
116
+ v = (v / spec.chords[0].length) * attack * Math.exp(-t * 4) * 0.45
117
+ v += Math.sin(2 * Math.PI * (70 + 60 * Math.exp(-t * 30)) * t) * attack * Math.exp(-t * 18)
118
+ const tail = Math.min(1, (total - i) / (RATE * 0.01))
119
+ left[i] = right[i] = v * tail
120
+ }
121
+ // The loudest 5 ms, as the sounds measure theirs: what a listener hears as the hit; moved onto a frame
122
+ const heard = measuredPeak(left, right)
123
+ const frame = fps.d / fps.n
124
+ const pad = Math.round((Math.ceil(heard / frame - 1e-9) * frame - heard) * RATE)
125
+ const padded = (channel) => Float32Array.from([...new Float32Array(pad), ...channel])
126
+ writeWav(file, padded(left), padded(right))
127
+ return { file, peak: heard + pad / RATE }
128
+ }
129
+
130
+ /** The loudest 5 ms of a pair of channels, as the time of that window's middle in seconds. */
131
+ export function measuredPeak(left, right) {
132
+ const window = Math.round(RATE / 200)
133
+ let best = 0
134
+ let at = 0
135
+ for (let start = 0; start + window <= left.length; start += window) {
136
+ let sum = 0
137
+ for (let i = start; i < start + window; i++) sum += left[i] * left[i] + right[i] * right[i]
138
+ if (sum > best) [best, at] = [sum, start + window / 2]
139
+ }
140
+ return at / RATE
141
+ }
142
+
85
143
  /** A stereo 16-bit WAV at 48 kHz, peaking at about -6 dBFS (the mix sets the level). */
86
144
  export function writeWav(file, left, right) {
87
145
  const total = left.length
@@ -9,6 +9,7 @@ import { existsSync } from "node:fs"
9
9
  import { join } from "node:path"
10
10
 
11
11
  import { platformId } from "../runtime/setup.js"
12
+ import { FONTS } from "./fonts.js"
12
13
  import { EngineFailure } from "./tool.js"
13
14
 
14
15
  /**
@@ -41,6 +42,16 @@ export const PACKS = {
41
42
  artifacts: ["depth-anything-v2-small"],
42
43
  licences: [{ item: "Depth Anything V2 Small", licence: "Apache-2.0" }],
43
44
  },
45
+ // TP7 (EDD-67): fonts for the type kit and every Indian script; no operation needs it, since
46
+ // a tile without it keeps the system stacks with a note (audit §6 rule 7)
47
+ "pack-fonts": {
48
+ title: "Fonts",
49
+ does: "the type kit's faces and a font for each Indian script, so text draws the same on every computer",
50
+ ops: [],
51
+ filters: [],
52
+ artifacts: Object.keys(FONTS),
53
+ licences: Object.values(FONTS).map((font) => ({ item: font.family.replace(/^Kriya /, ""), licence: "OFL-1.1" })),
54
+ },
44
55
  }
45
56
 
46
57
  export const packName = (id) => id.replace(/^pack-/, "")
@@ -0,0 +1,26 @@
1
+ // A reference's colour, matched by measurement (TP6, CRAFT_UPGRADE §4.1, EDD-65), behind
2
+ // editing.referenceIntent: the person's own footage is measured in OKLab and carried toward the
3
+ // reference's measured statistics by the same transport a shot match uses (color.js), within its
4
+ // limits, and baked into a `.cube` Kriya writes. This replaces reference.js's 8-bit-average
5
+ // shortcut when the switch is on. Only numbers come from the reference: the LUT is a function of
6
+ // two sets of statistics and holds no pixel of anyone's video.
7
+
8
+ import { cubeText, matchCube, MATCH_LIMITS, measureColour } from "./color.js"
9
+ import { runTool } from "./tool.js"
10
+
11
+ /**
12
+ * @param {string} file the person's own take
13
+ * @param {number} seconds its length
14
+ * @param {{ mean: number[], cov: number[][] }} colour an Edit DNA 2's colour
15
+ * @returns {Promise<{ cube: string, limited: boolean, apart: { lightness: number, chroma: number } }>} limited: the footage was further from the reference than a match may move it
16
+ */
17
+ export async function referenceMatch(file, seconds, colour, { run = runTool, signal, limits = MATCH_LIMITS } = {}) {
18
+ const own = await measureColour(file, { from: 0, to: Math.min(seconds, 120), frames: 24, run, signal })
19
+ return { ...referenceCube(own, colour, limits), own: { mean: own.mean } }
20
+ }
21
+
22
+ /** The LUT and how far apart the two were. Pure. */
23
+ export function referenceCube(own, colour, limits = MATCH_LIMITS) {
24
+ const apart = { lightness: Math.abs(colour.mean[0] - own.mean[0]), chroma: Math.hypot(colour.mean[1] - own.mean[1], colour.mean[2] - own.mean[2]) }
25
+ return { cube: cubeText({ ...matchCube(own, { mean: colour.mean, cov: colour.cov }, { limits }), title: "Kriya reference match" }), limited: apart.lightness > limits.lightness || apart.chroma > limits.chroma, apart }
26
+ }
@@ -2,7 +2,9 @@
2
2
  // intro, a hit for a cold open's end. Written sample by sample, so no one else's sound is
3
3
  // in them, and each knows where its peak is: add_sfx lands that peak on the cut.
4
4
 
5
- import { writeWav } from "./music-bed.js"
5
+ import { measuredPeak, writeWav } from "./music-bed.js"
6
+
7
+ export { measuredPeak }
6
8
 
7
9
  const RATE = 48_000
8
10
  const FLICKS = 705_600_000
@@ -15,11 +17,43 @@ export const SFX = {
15
17
  hit: { seconds: 0.9, peak: 0.02 },
16
18
  }
17
19
 
20
+ // TP10 (CRAFT_UPGRADE §8, EDD-69): sixteen more, still written by code. Each is a tone or a noise under
21
+ // an envelope; its peak is measured from its own samples when it is written, so add_sfx lands the loudest
22
+ // moment where it is asked. The four above stay byte for byte what they were
23
+ const bell = (f, t) => Math.sin(2 * Math.PI * f * t) + 0.5 * Math.sin(2 * Math.PI * f * 2.76 * t) + 0.25 * Math.sin(2 * Math.PI * f * 5.4 * t)
24
+ const gauss = (t, at, width) => Math.exp(-(((t - at) / width) ** 2))
25
+ const phaseOf = (from, to, t, seconds) => (2 * Math.PI * from * seconds * ((to / from) ** (t / seconds) - 1)) / Math.log(to / from)
26
+ export const MORE_SFX = {
27
+ click: { seconds: 0.05, group: "cut", make: (t, x, noise) => noise() * Math.exp(-t * 900) },
28
+ tick: { seconds: 0.08, group: "cut", make: (t) => Math.sin(2 * Math.PI * 2000 * t) * Math.exp(-t * 120) },
29
+ snap: { seconds: 0.12, group: "cut", make: (t, x, noise) => (noise() * 0.6 + Math.sin(2 * Math.PI * 1500 * t)) * Math.exp(-t * 70) },
30
+ blip: { seconds: 0.09, group: "cut", make: (t) => Math.sin(2 * Math.PI * 1200 * t) * Math.min(1, t * 400) * Math.exp(-t * 40) },
31
+ swish: { seconds: 0.4, group: "cut", make: (t, x, noise, low) => low(noise(), 0.05 + 0.4 * gauss(t, 0.2, 0.08)) * gauss(t, 0.2, 0.07) },
32
+ zap: { seconds: 0.25, group: "cut", make: (t) => Math.sin(phaseOf(2000, 200, t, 0.25)) * Math.min(1, t * 300) * Math.exp(-t * 14) },
33
+ ding: { seconds: 1, group: "accent", make: (t) => bell(1760, t) * Math.min(1, t * 500) * Math.exp(-t * 4) },
34
+ chime: { seconds: 1.4, group: "accent", make: (t) => (bell(1046.5, t) + bell(1318.5, t) * 0.7) * Math.min(1, t * 500) * Math.exp(-t * 3) },
35
+ shimmer: { seconds: 0.8, group: "accent", make: (t, x, noise, low) => (noise() - low(noise(), 0.2)) * (0.6 + 0.4 * Math.sin(2 * Math.PI * 18 * t)) * gauss(t, 0.4, 0.15) },
36
+ thud: { seconds: 0.5, group: "intro", make: (t) => Math.sin(2 * Math.PI * (55 + 40 * Math.exp(-t * 30)) * t) * Math.min(1, t * 400) * Math.exp(-t * 9) },
37
+ boom: { seconds: 1.4, group: "intro", make: (t, x, noise) => (Math.sin(2 * Math.PI * (40 + 70 * Math.exp(-t * 12)) * t) + noise() * Math.exp(-t * 40) * 0.3) * Math.min(1, t * 300) * Math.exp(-t * 3.5) },
38
+ drop: { seconds: 0.7, group: "intro", make: (t) => Math.sin(phaseOf(800, 80, t, 0.7)) * Math.min(1, t * 200) * Math.exp(-t * 4) },
39
+ swell: { seconds: 1.2, group: "intro", make: (t, x, noise, low) => (low(noise(), 0.05 + 0.3 * x) * 0.7 + 0.3 * Math.sin(2 * Math.PI * 220 * t)) * x ** 2 * (t < 1.15 ? 1 : Math.max(0, 1 - (t - 1.15) / 0.05)) },
40
+ sweepUp: { seconds: 0.6, group: "intro", make: (t) => Math.sin(phaseOf(300, 2000, t, 0.6)) * gauss(t, 0.45, 0.12) },
41
+ sweepDown: { seconds: 0.6, group: "cut", make: (t) => Math.sin(phaseOf(2000, 300, t, 0.6)) * gauss(t, 0.15, 0.1) },
42
+ rumble: { seconds: 1.2, group: "intro", make: (t, x, noise, low) => low(noise(), 0.01) * 6 * gauss(t, 0.6, 0.3) },
43
+ }
44
+ /** Every sound Kriya can write, by kind: the first four, then TP10's. */
45
+ export const SOUNDS = [...Object.keys(SFX), ...Object.keys(MORE_SFX)]
46
+ /** Kinds for the cut, for an intro and as accents, as the make and the plan offer them (TP10, with editing.craft). */
47
+ export const CUT_SOUNDS = ["whoosh", "pop", ...Object.entries(MORE_SFX).filter(([, s]) => s.group === "cut").map(([k]) => k)]
48
+ export const INTRO_SOUNDS = ["riser", "hit", ...Object.entries(MORE_SFX).filter(([, s]) => s.group === "intro").map(([k]) => k)]
49
+
50
+
18
51
  /**
19
52
  * Writes one effect as a stereo WAV.
20
53
  * @returns {{ file: string, peak: number }} peak in flicks from the file's start
21
54
  */
22
55
  export function writeSfx(file, kind) {
56
+ if (Object.hasOwn(MORE_SFX, kind)) return writeMore(file, kind)
23
57
  const spec = SFX[kind]
24
58
  if (!spec) throw new RangeError(`There is no "${kind}" sound.`)
25
59
  const total = Math.round(spec.seconds * RATE)
@@ -61,3 +95,24 @@ export function writeSfx(file, kind) {
61
95
  writeWav(file, left, right)
62
96
  return { file, peak: Math.round(spec.peak * FLICKS) }
63
97
  }
98
+
99
+ function writeMore(file, kind) {
100
+ const spec = MORE_SFX[kind]
101
+ const total = Math.round(spec.seconds * RATE)
102
+ const left = new Float32Array(total)
103
+ const right = new Float32Array(total)
104
+ let seed = 0x6d2b79f5
105
+ const noise = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32) * 2 - 1
106
+ let state = 0
107
+ const low = (input, k) => (state += k * (input - state))
108
+ for (let i = 0; i < total; i++) {
109
+ const t = i / RATE
110
+ const v = spec.make(t, t / spec.seconds, noise, low)
111
+ // A short fade at the very end, so no sound stops on a click
112
+ const tail = Math.min(1, (total - i) / (RATE * 0.004))
113
+ left[i] = v * tail
114
+ right[i] = v * tail
115
+ }
116
+ writeWav(file, left, right)
117
+ return { file, peak: Math.round(measuredPeak(left, right) * FLICKS) }
118
+ }
@@ -9,15 +9,31 @@ import { childEnv } from "../runtime/setup.js"
9
9
 
10
10
  const TAIL = 4000
11
11
 
12
- // ES-03: FFmpeg and FFprobe get no network at all where the OS can say so (macOS); the
13
- // protocol whitelist is the other barrier, and the only one elsewhere (EQ-11)
12
+ // ES-03: FFmpeg and FFprobe get no network at all where the OS can say so: macOS's sandbox-exec, and
13
+ // (TP11) Linux's bubblewrap with a network namespace of its own. On Linux a media tool never runs without
14
+ // it. Windows has no runner yet (EQ-11): there the protocol whitelist is the only barrier, as before, and
15
+ // nothing calls that confined
14
16
  const SANDBOX_EXEC = "/usr/bin/sandbox-exec"
15
17
  const NO_NETWORK = "(version 1)(allow default)(deny network*)"
18
+ const BWRAP_PATHS = ["/usr/bin/bwrap", "/bin/bwrap", "/usr/local/bin/bwrap"]
16
19
  const CONFINED = new Set(["ffmpeg", "ffprobe"])
17
- const canConfine = process.platform === "darwin" && existsSync(SANDBOX_EXEC)
18
20
 
19
- /** The command line that actually runs: a media tool wrapped in the no-network profile. */
20
- export const confined = (command, args) => (canConfine && CONFINED.has(basename(command)) ? [SANDBOX_EXEC, ["-p", NO_NETWORK, command, ...args]] : [command, args])
21
+ /**
22
+ * The command line that actually runs: a media tool wrapped in the no-network profile.
23
+ * @returns {[string, string[]]} throws no_confinement for a media tool on Linux without bubblewrap
24
+ */
25
+ export function confined(command, args, { platform = process.platform, exists = existsSync } = {}) {
26
+ const name = basename(command).replace(/\.exe$/i, "")
27
+ if (!CONFINED.has(name)) return [command, args]
28
+ if (platform === "darwin") return exists(SANDBOX_EXEC) ? [SANDBOX_EXEC, ["-p", NO_NETWORK, command, ...args]] : [command, args]
29
+ if (platform === "linux") {
30
+ const bwrap = BWRAP_PATHS.find((path) => exists(path))
31
+ if (!bwrap) throw new EngineFailure("environment", "no_confinement", `${name} runs without network inside bubblewrap on Linux, and it isn't installed. Install the bubblewrap package (bwrap).`)
32
+ // The files where they are (FFmpeg reads the person's footage and writes the cache), the network gone
33
+ return [bwrap, ["--die-with-parent", "--unshare-net", "--bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--", command, ...args]]
34
+ }
35
+ return [command, args]
36
+ }
21
37
 
22
38
  export class EngineFailure extends Error {
23
39
  /**