@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
@@ -0,0 +1,33 @@
1
+ // The clips a computer advertises for an offered folder (TP11, CRAFT_UPGRADE §9): each clip's number and
2
+ // the person's own label, read from the folder's editing project on this computer. Never a path, a file
3
+ // name, a transcript or a reference: Tavi may only name an order by what the person can see in the Studio.
4
+ // Loaded lazily by the daemon, only with KRIYA_EDIT on and after Kriya advertised taviOrder (rule 17).
5
+
6
+ import { readFileSync } from "node:fs"
7
+ import { dirname } from "node:path"
8
+ import { join } from "node:path"
9
+
10
+ import { clipNumbers, cleanLabel } from "../core/project.js"
11
+ import { editHome } from "./paths.js"
12
+
13
+ export const MAX_CLIPS = 50
14
+
15
+ /** @returns {{ n: number, label?: string }[]} empty when the folder has no project or it can't be read */
16
+ export function advertisedClips(folder, { home } = {}) {
17
+ try {
18
+ const registry = JSON.parse(readFileSync(join(editHome(home), "projects.json"), "utf8"))
19
+ const entry = registry.find((item) => item && typeof item.file === "string" && dirname(item.file) === folder)
20
+ if (!entry) return []
21
+ const project = JSON.parse(readFileSync(entry.file, "utf8"))
22
+ const numbers = clipNumbers(project)
23
+ return project.assets
24
+ .filter((asset) => numbers.has(asset.id) && asset.kind === "video")
25
+ .map((asset) => {
26
+ const label = cleanLabel(asset.label)
27
+ return { n: numbers.get(asset.id), ...(label ? { label } : {}) }
28
+ })
29
+ .slice(0, MAX_CLIPS)
30
+ } catch {
31
+ return []
32
+ }
33
+ }
@@ -25,7 +25,7 @@ export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
25
25
  }
26
26
  }
27
27
  // The asset of an index job, so the Studio's bin shows its progress on the right file
28
- const view = (state, row) => ({ id: idOf(state, row.id), project: state.id, kind: row.kind, status: row.status, progress: row.progress, error: row.error, output: row.dispatch, ...(row.kind === "index" ? { asset: assetOf(row) } : {}) })
28
+ const view = (state, row) => ({ id: idOf(state, row.id), project: state.id, kind: row.kind, status: row.status, progress: row.progress, error: row.error, output: row.dispatch, ...(row.kind === "index" || row.kind === "reference" ? { asset: assetOf(row) } : {}) })
29
29
 
30
30
  async function run(state, number, request) {
31
31
  const id = idOf(state, number)
@@ -44,13 +44,19 @@ export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
44
44
  const output =
45
45
  request.kind === "index"
46
46
  ? JSON.stringify(await projects.indexAsset(state, request.asset, { signal: controller.signal, onStep }))
47
+ : request.kind === "reference"
48
+ ? // TP6: a reference's Edit DNA 2, measured only here, as a job with progress and a cancel (EH-73)
49
+ JSON.stringify(await projects.measureReference(state, request.asset, { job: number, signal: controller.signal, onStep }))
47
50
  : request.kind === "make"
48
- ? JSON.stringify(await projects.make(state, request, { job: number, signal: controller.signal, onStep, ...(request.dispatch && beforeStory && { beforeStory: (...args) => beforeStory(request, ...args) }) }))
51
+ ? JSON.stringify(await projects.make(state, request, { job: number, signal: controller.signal, onStep, onLive: (event) => emit("live", { job: id, project: state.id, ...event }), ...(request.dispatch && beforeStory && { beforeStory: (...args) => beforeStory(request, ...args) }) }))
52
+ : request.kind === "openings"
53
+ ? // TP8: three short openings to choose from, only with editing.directorLoop on
54
+ JSON.stringify(await projects.openings(state, request, { job: number, signal: controller.signal, onStep }))
49
55
  : request.kind === "revise"
50
56
  ? JSON.stringify(await projects.revise(state, request, { job: number, signal: controller.signal, onStep }))
51
57
  : request.kind === "replay"
52
58
  ? JSON.stringify(await projects.replay(state, request.of, { job: number, signal: controller.signal, onStep }))
53
- : (await state.engine.render({ ...request, job: number, signal: controller.signal, onStep, project: request.project ?? versionOf(state, number) })).file
59
+ : (await state.engine.render({ ...request, job: number, signal: controller.signal, onStep, project: request.project ?? versionOf(state, number), partial: request.quality === "draft" && (await projects.features?.())?.livePreview === true })).file
54
60
  update({ status: "done", progress: 100, dispatch: output, finished_at: new Date().toISOString() })
55
61
  } catch (error) {
56
62
  if (controller.signal.aborted) update({ status: "canceled", finished_at: new Date().toISOString() })
@@ -0,0 +1,134 @@
1
+ // "Watch the Director edit" (editing.livePreview): the make's own operations, grouped by
2
+ // what they do and applied in order onto the cut it started from, so the Studio can show the
3
+ // film as each layer lands, live while a make runs and as a replay after. Every layer is real
4
+ // code state: the operations the Director produced, applied by apply(). Nothing here writes
5
+ // the project's history: the views are previews, never evidence (the render and gates are).
6
+
7
+ import { apply } from "../core/ops.js"
8
+ import { solve } from "../core/solver.js"
9
+ import { describe } from "../director/revise.js"
10
+ import { previewOf } from "./preview.js"
11
+
12
+ /** The layers, in the order they're shown. `raw` is the cut before the make. */
13
+ export const LAYERS = [
14
+ { id: "raw", label: "Raw footage" },
15
+ { id: "cuts", label: "Cuts & pacing" },
16
+ { id: "broll", label: "B-roll & transitions" },
17
+ { id: "look", label: "Look & filters" },
18
+ { id: "captions", label: "Captions & motion" },
19
+ { id: "audio", label: "Audio mix" },
20
+ ]
21
+ const RANK = Object.fromEntries(LAYERS.map((layer, i) => [layer.id, i]))
22
+ const OF = {
23
+ broll: ["place_broll", "place_over", "transition"],
24
+ look: ["grade", "match_color", "apply_lut", "fix_exposure", "set_look", "add_effect", "add_adjustment", "remove_effect"],
25
+ captions: ["caption_style", "caption_edit", "caption_emphasis", "add_title", "add_lower_third", "add_motion", "text_behind", "set_type_kit"],
26
+ audio: ["add_sfx", "set_music", "music_shape", "duck", "clean_voice", "set_level", "room_tone"],
27
+ }
28
+ const LAYER_OF = new Map(Object.entries(OF).flatMap(([layer, ops]) => ops.map((op) => [op, layer])))
29
+ // Everything else (cuts, framing, assets, the brief) goes in the first layer: later ones may need it
30
+ export const layerOf = (op) => LAYER_OF.get(op?.op) ?? "cuts"
31
+
32
+ /**
33
+ * Each layer's project: layer k is the start with every operation of layer ≤ k applied, in the
34
+ * make's own order. A prefix that doesn't apply on its own is said, and the layer shows the one before.
35
+ * @returns {{ id: string, label: string, ops: number, changes: string[], project: object, skipped?: string }[]}
36
+ */
37
+ export function layersOf(before, ops, index) {
38
+ const out = [{ ...LAYERS[0], ops: 0, changes: [], project: before }]
39
+ let last = before
40
+ for (const layer of LAYERS.slice(1)) {
41
+ const own = ops.filter((op) => layerOf(op) === layer.id)
42
+ const upTo = ops.filter((op) => RANK[layerOf(op)] <= RANK[layer.id])
43
+ const changes = own.filter((op) => !(op.op === "caption_style" && op.words?.length)).slice(0, 4).map((op) => safeDescribe(op, index))
44
+ if (!own.length) {
45
+ out.push({ ...layer, ops: 0, changes, project: last })
46
+ continue
47
+ }
48
+ const step = apply(before, upTo, { index, author: "agent" })
49
+ if (step.applied) last = step.project
50
+ out.push({ ...layer, ops: own.length, changes, project: last, ...(step.applied ? {} : { skipped: step.diagnostics[0]?.message ?? "it doesn't apply on its own" }) })
51
+ }
52
+ return out
53
+ }
54
+
55
+ function safeDescribe(op, index) {
56
+ try {
57
+ return describe(op, index)
58
+ } catch {
59
+ return op.op.replaceAll("_", " ")
60
+ }
61
+ }
62
+
63
+ /** What the monitor and the timeline draw for a project: its preview plan and the solver's timeline. */
64
+ export function viewOf(project, index, { runtimeVersion, tiles, fonts }) {
65
+ const { picture, audio, overlays, captions, duration } = solve(project, index)
66
+ return { preview: previewOf(project, index, { runtimeVersion, tiles, ...(fonts ? { fonts } : {}) }), timeline: { picture, audio, overlays, captions, duration } }
67
+ }
68
+
69
+ /**
70
+ * The newest finished make whose cut is in the project's history, as the agent's entry it landed
71
+ * as: its parent is the cut it started from, its operations what it did. Null when there's none.
72
+ */
73
+ export function lastMadeEntry(rows, log) {
74
+ for (const row of [...rows].reverse()) {
75
+ if (row.kind !== "make") continue
76
+ let head = null
77
+ try {
78
+ head = JSON.parse(row.dispatch ?? "{}").head ?? null
79
+ } catch {}
80
+ const entry = log.entries.find((e) => e.id === head && e.author === "agent")
81
+ if (entry) return { entry, job: row.id }
82
+ }
83
+ return { entry: null, job: null }
84
+ }
85
+
86
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`
87
+
88
+ /** A gate result as the Studio lists it: its id, status and the gate's own message, nothing else. */
89
+ export const gateRow = ({ id, status, severity, message }) => ({ id, status, severity, ...(message ? { message } : {}) })
90
+
91
+ /**
92
+ * The make's live events (makeReel's onLive) turned into what the Studio shows, sent through `send`.
93
+ * A view that can't be drawn is left out; a failure here never touches the make.
94
+ */
95
+ export function liveFeed({ index, runtimeVersion, tiles, fonts, send }) {
96
+ const view = (project) => {
97
+ try {
98
+ return viewOf(project, index, { runtimeVersion, tiles, fonts })
99
+ } catch {
100
+ return {}
101
+ }
102
+ }
103
+ return (event) => {
104
+ try {
105
+ if (event.stage === "plan") {
106
+ send({ stage: "story", text: `Chose the story: ${plural(event.ops.length, "planned change")}${event.round > 1 ? ` (round ${event.round})` : ""}.`, round: event.round })
107
+ for (const layer of layersOf(event.before, event.ops, index).slice(1)) {
108
+ if (!layer.ops) continue
109
+ send({ stage: layer.id, text: `${layer.label}: ${plural(layer.ops, "change")}.`, changes: layer.changes, round: event.round, ...(layer.skipped ? { skipped: layer.skipped } : {}), ...view(layer.project) })
110
+ }
111
+ return
112
+ }
113
+ if (event.stage === "render") return send({ stage: "render", text: event.repair ? "Rendering a repaired cut to check it again." : "Rendering the master to check it.", ...(event.project ? view(event.project) : {}) })
114
+ if (event.stage === "check") {
115
+ const gates = (event.gates ?? []).map(gateRow)
116
+ const passed = gates.filter((g) => g.status === "passed").length
117
+ const failed = gates.filter((g) => g.status === "failed").length
118
+ const rest = gates.length - passed - failed
119
+ return send({ stage: "check", text: `Checked: ${passed} passed, ${failed} failed${rest ? `, ${rest} not checked or not applicable` : ""}.`, gates })
120
+ }
121
+ if (event.stage === "repair") {
122
+ const attempts = (event.attempts ?? []).map((a) => ({ round: a.round, accepted: a.accepted === true, fixes: (a.fixes ?? []).map((f) => f.why ?? f.kind ?? "fix"), ...(a.reason ? { reason: a.reason } : {}) }))
123
+ const kept = attempts.filter((a) => a.accepted).length
124
+ return send({ stage: "repair", text: attempts.length ? `Repairs: ${plural(attempts.length, "round")} tried, ${kept} kept.` : "No repair could help: this is yours to decide.", attempts, ...(event.project ? view(event.project) : {}) })
125
+ }
126
+ if (event.stage === "watch") {
127
+ const rounds = (event.rounds ?? []).map((r) => ({ round: r.round, kept: r.kept === true, fixes: (r.fixes ?? []).map((f) => f.kind), ...(r.reason ? { reason: r.reason } : {}) }))
128
+ return send({ stage: "watch", text: `Watched the draft: ${plural(rounds.length, "round")}, ${rounds.filter((r) => r.kept).length} kept.`, rounds, ...(event.project ? view(event.project) : {}) })
129
+ }
130
+ } catch {
131
+ // A live view is a courtesy: the make goes on without it
132
+ }
133
+ }
134
+ }
@@ -1,7 +1,8 @@
1
1
  // The Edit Host: one process per machine, detached, owning every job (EDD-03). It
2
2
  // holds a lock, listens on loopback and on an owner-only socket, and exits when idle.
3
3
 
4
- import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
4
+ import { randomBytes } from "node:crypto"
5
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
5
6
  import { createServer } from "node:http"
6
7
  import { homedir } from "node:os"
7
8
  import { delimiter } from "node:path"
@@ -12,7 +13,7 @@ import { createScheduler, DEFAULT_SLOTS } from "../graph/scheduler.js"
12
13
  import { createGovernor } from "../loop/governor.js"
13
14
  import { kriyaHome } from "../../paths.js"
14
15
  import { createJobs } from "./jobs.js"
15
- import { codeStamp, editHome, isPipe, lockPath, portPath, socketPath } from "./paths.js"
16
+ import { codeStamp, editHome, isPipe, lockPath, portPath, socketPath, tokenPath } from "./paths.js"
16
17
  import { createProjects } from "./projects.js"
17
18
  import { createHandler } from "./server.js"
18
19
  import { createTavi } from "./tavi.js"
@@ -78,7 +79,12 @@ let inFlight = 0 // a request still running isn't idle, however long it takes
78
79
  let port = 0
79
80
  // What code this process runs, so an outdated Host is replaced once it's idle (client.js)
80
81
  const stamp = codeStamp()
81
- const handle = createHandler({ home, roots, projects, jobs, tavi, tools: readTools, tokenTtlMs, port: () => port, stamp, busy: () => jobs.count() + tavi.pending(), onActivity: (change = 0) => ((inFlight += change), (lastActive = Date.now())), onStop: () => shutdown(), onLive: () => (liveAt = Date.now()), sse, log, pid: process.pid })
82
+ // TP11: this launch's secret for its own channel (a Windows pipe takes anyone's connection), written owner-only
83
+ // and atomically before the channel opens, so a command never meets a Host whose token isn't on disk yet
84
+ const ipcToken = randomBytes(32).toString("hex")
85
+ writeFileSync(`${tokenPath(home)}.tmp`, ipcToken, { mode: 0o600 })
86
+ renameSync(`${tokenPath(home)}.tmp`, tokenPath(home))
87
+ const handle = createHandler({ home, ipcToken, roots, projects, jobs, tavi, tools: readTools, tokenTtlMs, port: () => port, stamp, busy: () => jobs.count() + tavi.pending(), onActivity: (change = 0) => ((inFlight += change), (lastActive = Date.now())), onStop: () => shutdown(), onLive: () => (liveAt = Date.now()), sse, log, pid: process.pid })
82
88
  const web = createServer((req, res) => handle(req, res, false))
83
89
  const local = createServer((req, res) => handle(req, res, true))
84
90
 
@@ -92,6 +98,7 @@ function shutdown() {
92
98
  server.closeAllConnections()
93
99
  }
94
100
  if (!isPipe(socketPath(home))) rmSync(socketPath(home), { force: true })
101
+ rmSync(tokenPath(home), { force: true })
95
102
  tavi.close()
96
103
  watcher.close()
97
104
  projects.close()
@@ -1,7 +1,7 @@
1
1
  // Where the Host keeps things (ARCHITECTURE §5): never in a synced folder (EF-28).
2
2
 
3
3
  import { createHash } from "node:crypto"
4
- import { readdirSync, statSync } from "node:fs"
4
+ import { readdirSync, readFileSync, statSync } from "node:fs"
5
5
  import { join, resolve } from "node:path"
6
6
 
7
7
  import { kriyaHome } from "../../paths.js"
@@ -14,14 +14,32 @@ export const isPipe = (path) => path.startsWith(PIPE)
14
14
  * Where the Host listens for this computer's own commands. A Unix socket in the Host's folder;
15
15
  * on Windows, which has none there, a named pipe, one per Kriya home (a hash of its path,
16
16
  * which Windows compares without case).
17
- * shortcut: a pipe gets Windows' default access rules, not the socket's owner-only mode; a pipe
18
- * limited to the signed-in person needs a native call Node doesn't offer. Not yet run on Windows.
17
+ * A pipe gets Windows' default access rules, not the socket's owner-only mode, and Node can't narrow them;
18
+ * so (TP11) every command on the channel carries the Host's per-launch token (tokenPath), which only this
19
+ * account can read. Not yet run on Windows (EQ-11).
19
20
  */
20
21
  export function socketPath(home = kriyaHome(), platform = process.platform) {
21
22
  if (platform !== "win32") return join(editHome(home), "host.sock")
22
23
  return `${PIPE}kriya-edit-host-${createHash("sha256").update(resolve(home).toLowerCase()).digest("hex").slice(0, 16)}`
23
24
  }
24
25
  export const lockPath = (home) => join(editHome(home), "host.lock")
26
+ /** TP11: the running Host's secret for its own channel, made fresh at each launch, readable by its owner only. */
27
+ export const tokenPath = (home) => join(editHome(home), "host.token")
28
+ export const TOKEN_HEADER = "x-kriya-edit-token"
29
+ /** The running Host's token, or null when none is there (no Host yet, or one from before TP11). */
30
+ export function hostToken(home = kriyaHome()) {
31
+ try {
32
+ const token = readFileSync(tokenPath(home), "utf8").trim()
33
+ return /^[a-f0-9]{64}$/.test(token) ? token : null
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+ /** The headers a command to the Host carries. */
39
+ export const hostHeaders = (home = kriyaHome()) => {
40
+ const token = hostToken(home)
41
+ return { host: "kriya-edit", ...(token ? { [TOKEN_HEADER]: token } : {}) }
42
+ }
25
43
  export const portPath = (home) => join(editHome(home), "port")
26
44
  export const logPath = (home) => join(editHome(home), "host.log")
27
45
 
@@ -0,0 +1,108 @@
1
+ // The live preview (TP3, CRAFT_UPGRADE §2, EDD-63): what the Studio's monitor needs to draw
2
+ // the film, taken from the draft's own compiled plan, so it shows what the render will make.
3
+ // Tiles are the renderer's own documents; transitions, framing, looks and sound are data the
4
+ // monitor draws. A preview is never evidence: the rendered file and its gates are.
5
+
6
+ import { busOf, duckEnvelope } from "../core/audio.js"
7
+ import { compile, wholeSegment } from "../core/plan.js"
8
+ import { EFFECTS as FX, valuesOf } from "../core/effects.js"
9
+ import { captionComposition } from "../engine/captions.js"
10
+ import { ENGINE_VERSION } from "../engine/index.js"
11
+ import { compositionFor } from "../engine/motion.js"
12
+
13
+ export const DUCK_RATE = 100 // the duck's gain curve, values per second, for WebAudio
14
+ const KEPT = 400 // tile documents a Host remembers per project (the latest previews')
15
+
16
+ // The tile pauses its animations at the time the monitor posts: no clock of its own, as the
17
+ // renderer seeks it (renderTileInChrome). It answers only its parent
18
+ const SYNC = `<script>addEventListener("message",(e)=>{if(e.source!==parent||typeof e.data?.t!=="number")return;for(const a of document.getAnimations()){a.pause();a.currentTime=e.data.t}})</script>`
19
+
20
+ // ET-HR-01's order, as the render layers them: behind-the-speaker text, then cards, then captions
21
+ const depthOf = (tile) => (tile.node.behind === true && !tile.front ? 0 : tile.kind === "caption" ? 2 : 1)
22
+
23
+ /**
24
+ * The monitor's plan of a project: one draft compile.
25
+ * @param {object} project
26
+ * @param {object} index
27
+ * @param {{ runtimeVersion: string, tiles?: Map<string, object> }} options tiles: where to remember documents for tileDocument()
28
+ */
29
+ export function previewOf(project, index, { runtimeVersion, tiles, fonts }) {
30
+ const plan = compile(project, index, { engineVersion: ENGINE_VERSION, runtimeVersion, ...(fonts ? { fonts } : {}) })
31
+ const whole = wholeSegment(plan)
32
+ const picture = whole.node.picture.map((item) => {
33
+ const frame = item.effects.find((e) => e.type === "frame")
34
+ const grade = item.effects.find((e) => e.type === "grade")
35
+ const lut = item.effects.some((e) => e.type === "lut") || grade?.match !== undefined
36
+ // TP5: each registry effect the monitor can approximate, as a CSS filter; the rest it leaves to the render
37
+ const css = cssOf(item.effects)
38
+ return {
39
+ asset: item.asset,
40
+ at: item.at,
41
+ end: item.end,
42
+ ...(frame ? { frame: frame.mode } : {}),
43
+ ...(grade ? { grade: Object.fromEntries(["gamma", "saturation", "lift", "gain", "ev", "temperature", "vibrance", "vignette"].filter((k) => grade[k] !== undefined).map((k) => [k, grade[k]])) } : {}),
44
+ // A LUT or a colour match isn't drawn by the monitor; it says so
45
+ ...(lut ? { lut: true } : {}),
46
+ ...(css.length ? { fx: css } : {}),
47
+ ...(item.enter ? { enter: { kind: item.enter.kind, duration: item.enter.duration, asset: item.enter.from.asset, source: item.enter.from.in } } : {}),
48
+ }
49
+ })
50
+ const drawn = plan.tiles.filter((tile) => !(tile.kind === "caption" && tile.node.style?.burn === true))
51
+ for (const tile of drawn) {
52
+ tiles?.delete(tile.key)
53
+ tiles?.set(tile.key, { tile, output: plan.output, canvas: plan.canvas })
54
+ }
55
+ while (tiles && tiles.size > KEPT) tiles.delete(tiles.keys().next().value)
56
+ const items = plan.audio.items.map((item) => {
57
+ const level = item.effects.find((e) => e.type === "level")
58
+ const fade = item.effects.find((e) => e.type === "fade")
59
+ return {
60
+ asset: item.asset,
61
+ bus: busOf(item.role),
62
+ at: item.at,
63
+ end: item.end,
64
+ in: item.in,
65
+ out: item.out,
66
+ ...(item.loop ? { loop: true } : {}),
67
+ ...(item.speed && item.speed.n !== item.speed.d ? { speed: item.speed } : {}),
68
+ ...(item.fit?.segments?.length ? { fit: { segments: item.fit.segments, crossfade: item.fit.crossfade } } : {}),
69
+ ...(level ? { db: level.db } : {}),
70
+ ...(fade?.in ? { fadeIn: fade.in } : {}),
71
+ ...(fade?.out ? { fadeOut: fade.out } : {}),
72
+ }
73
+ })
74
+ const { duck } = plan.audio
75
+ // Beats where the music plays them on the timeline, for a trimmed edge to snap to
76
+ const beats = []
77
+ for (const item of plan.audio.items.filter((i) => busOf(i.role) === "music")) {
78
+ const pieces = item.fit?.segments?.length ? item.fit.segments : [{ in: item.in, out: item.out }]
79
+ let start = item.at
80
+ for (const piece of pieces) {
81
+ for (const beat of index.beats ?? []) if (beat.asset === item.asset && beat.t >= piece.in && beat.t < piece.out && start + beat.t - piece.in < item.end) beats.push(start + beat.t - piece.in)
82
+ start += piece.out - piece.in - (item.fit?.crossfade ?? 0)
83
+ }
84
+ }
85
+ return {
86
+ output: plan.output,
87
+ canvas: plan.canvas,
88
+ duration: plan.duration,
89
+ picture,
90
+ ...(plan.adjustments?.length ? { adjust: plan.adjustments.map((a) => ({ at: a.at, end: a.end, fx: cssOf([a.fx]) })).filter((a) => a.fx.length) } : {}),
91
+ tiles: drawn.map((tile) => ({ key: tile.key, kind: tile.kind, at: tile.at, end: tile.end, depth: depthOf(tile) })),
92
+ audio: { items, ...(duck ? { duck: { rate: DUCK_RATE, curve: [...duckEnvelope(duck.speech, { duration: plan.duration, depth: duck.depth, attack: duck.attack, release: duck.release, rate: DUCK_RATE })].map((v) => Math.round(v * 1e4) / 1e4) } } : {}) },
93
+ beats: [...new Set(beats)].sort((a, b) => a - b),
94
+ keys: plan.keys,
95
+ }
96
+ }
97
+
98
+ function cssOf(effects) {
99
+ // TP9: an effect inside a drawn region isn't a filter on the whole picture, so the monitor leaves it to the render
100
+ return effects.filter((e) => e.type === "fx" && FX[e.id] && !e.region).map((e) => FX[e.id].preview(valuesOf(e.id, e.params).values ?? {})).filter(Boolean)
101
+ }
102
+
103
+ /** A tile's own document, as the render draws it, with the monitor's time listener. Null when unknown. */
104
+ export function tileDocument(tiles, key) {
105
+ const found = typeof key === "string" && /^[0-9a-f]{64}$/.test(key) ? tiles.get(key) : undefined
106
+ if (!found) return null
107
+ return compositionFor(found.tile, { output: found.output, canvas: found.canvas }, captionComposition).replace("</body>", `${SYNC}</body>`)
108
+ }