@kriya-ai/harness 0.0.0-stage → 0.2.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 (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,220 @@
1
+ // Handoff (EDIT_ENGINE §11): editors can always leave with their work. Paths are
2
+ // relative; what a format can't carry is listed, never silently dropped.
3
+
4
+ import { clockTime, flicksToFrames, FLICKS, fractionSeconds, frameFlicks, timecode } from "./time.js"
5
+
6
+ const OTIO_BASE = { effects: [], markers: [], enabled: true, metadata: {} }
7
+
8
+ const baseName = (path) => path.split(/[\\/]/).at(-1)
9
+ const assetOf = (project, id) => project.assets.find((a) => a.id === id)
10
+ const isAbsolute = (path) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path)
11
+
12
+ /** Relative path of an asset inside the handoff package; two files of one name get their asset id in front. */
13
+ function mediaPath(project, { id, path }) {
14
+ if (!isAbsolute(path)) return path
15
+ const name = baseName(path)
16
+ const shared = project.assets.some((a) => a.id !== id && isAbsolute(a.path) && baseName(a.path) === name)
17
+ return shared ? `media/${id}-${name}` : `media/${name}`
18
+ }
19
+
20
+ const sourced = (timeline) => [...timeline.picture, ...timeline.overlays.filter((o) => o.asset), ...timeline.audio]
21
+
22
+ /** What to relink: each asset the timeline uses, once. */
23
+ export function handoffManifest(project, timeline) {
24
+ return [...new Set(sourced(timeline).map((item) => item.asset))].map((id) => {
25
+ const asset = assetOf(project, id)
26
+ return { asset: id, path: mediaPath(project, asset), fingerprint: asset.fingerprint, ...(asset.sha256 ? { sha256: asset.sha256 } : {}) }
27
+ })
28
+ }
29
+
30
+ // Exact: frames at the canvas rate when it fits, otherwise flicks as OTIO's own rate
31
+ function rationalTime(t, fps) {
32
+ const frame = frameFlicks(fps)
33
+ const fits = frame === null ? false : t % frame === 0
34
+ return { OTIO_SCHEMA: "RationalTime.1", rate: fits ? fps.n / fps.d : FLICKS, value: fits ? t / frame : t }
35
+ }
36
+
37
+ const timeRange = (start, duration, fps) => ({ OTIO_SCHEMA: "TimeRange.1", start_time: rationalTime(start, fps), duration: rationalTime(duration, fps) })
38
+
39
+ function otioEffects(item) {
40
+ const common = { name: "", metadata: {} }
41
+ if (item.hold) return [{ OTIO_SCHEMA: "FreezeFrame.1", ...common, effect_name: "FreezeFrame", time_scalar: 0 }]
42
+ if (item.speed && item.speed.n !== item.speed.d) return [{ OTIO_SCHEMA: "LinearTimeWarp.1", ...common, effect_name: "LinearTimeWarp", time_scalar: item.speed.n / item.speed.d }]
43
+ return []
44
+ }
45
+
46
+ function otioTrack(project, name, kind, items, fps) {
47
+ const children = []
48
+ let cursor = 0
49
+ for (const item of items) {
50
+ if (item.at > cursor) children.push({ OTIO_SCHEMA: "Gap.1", name: "", source_range: timeRange(0, item.at - cursor, fps), ...OTIO_BASE })
51
+ const asset = assetOf(project, item.asset)
52
+ children.push({
53
+ OTIO_SCHEMA: "Clip.2",
54
+ name: item.clip,
55
+ source_range: timeRange(item.in, item.end - item.at, fps),
56
+ media_references: { DEFAULT_MEDIA: { OTIO_SCHEMA: "ExternalReference.1", name: baseName(asset.path), target_url: mediaPath(project, asset), available_range: null, available_image_bounds: null, metadata: {} } },
57
+ active_media_reference_key: "DEFAULT_MEDIA",
58
+ ...OTIO_BASE,
59
+ effects: otioEffects(item),
60
+ })
61
+ cursor = item.end
62
+ }
63
+ return { OTIO_SCHEMA: "Track.1", name, kind, source_range: null, children, ...OTIO_BASE }
64
+ }
65
+
66
+ // A track can't hold overlaps, so overlapping items go to further tracks of that role
67
+ function lanes(items) {
68
+ const result = []
69
+ for (const item of [...items].sort((a, b) => a.at - b.at)) {
70
+ const lane = result.find((list) => list.at(-1).end <= item.at)
71
+ if (lane) lane.push(item)
72
+ else result.push([item])
73
+ }
74
+ return result
75
+ }
76
+
77
+ /**
78
+ * The sequence's markers on the timeline, from a time or a word; one whose word was cut is listed as lost.
79
+ * @returns {{ markers: { name: string, at: number }[], lost: { clip: string, reason: string }[] }}
80
+ */
81
+ export function timelineMarkers(project, index, timeline) {
82
+ const words = new Map((index?.words ?? []).map((w) => [w.id, w]))
83
+ const markers = []
84
+ const lost = []
85
+ for (const marker of project.sequences.find((q) => q.id === project.active).markers) {
86
+ let at = typeof marker.at === "number" ? marker.at : null
87
+ const word = words.get(marker.at.word)
88
+ if (word) {
89
+ const t = marker.at.edge === "end" ? word.end : word.start
90
+ const piece = timeline.picture.find((p) => !p.hold && p.asset === word.asset && p.in <= t && t < p.out)
91
+ if (piece) at = piece.at + Math.round(((t - piece.in) * piece.speed.d) / piece.speed.n)
92
+ }
93
+ if (at === null || at < 0 || at >= timeline.duration) lost.push({ clip: marker.id, reason: `marker "${marker.name}" isn't on the timeline any more` })
94
+ else markers.push({ name: marker.name, at: snapTo(at, timeline.fps) })
95
+ }
96
+ return { markers: markers.sort((a, b) => a.at - b.at), lost }
97
+ }
98
+
99
+ // The frame a time falls on, as flicks: FCPXML and NLEs place edits on frames
100
+ function snapTo(t, fps) {
101
+ const frame = frameFlicks(fps)
102
+ return frame === null ? t : Math.round(t / frame) * frame
103
+ }
104
+
105
+ /** @param {{ name: string, at: number }[]} [markers] chapters, as markers on the whole timeline */
106
+ export function toOtio(project, timeline, markers = []) {
107
+ const { fps } = timeline
108
+ const group = (items, name, kind) => lanes(items).map((lane, i) => otioTrack(project, i === 0 ? name : `${name} ${i + 1}`, kind, lane, fps))
109
+ const footage = timeline.overlays.filter((o) => o.asset)
110
+ const roles = [...new Set(footage.map((o) => o.role))]
111
+ const sounds = [...new Set(timeline.audio.map((a) => a.role))]
112
+ const children = [
113
+ ...group(timeline.picture, "base", "Video"),
114
+ ...roles.flatMap((role) => group(footage.filter((o) => o.role === role), role, "Video")),
115
+ ...sounds.flatMap((role) => group(timeline.audio.filter((a) => a.role === role), role, "Audio")),
116
+ ]
117
+ const marks = markers.map((m) => ({ OTIO_SCHEMA: "Marker.2", name: m.name, marked_range: timeRange(m.at, 0, fps), color: "RED", comment: "", metadata: {} }))
118
+ const stack = { OTIO_SCHEMA: "Stack.1", name: "tracks", source_range: null, children, ...OTIO_BASE, markers: marks }
119
+ return `${JSON.stringify({ OTIO_SCHEMA: "Timeline.1", name: project.name, global_start_time: null, metadata: {}, tracks: stack }, null, 2)}\n`
120
+ }
121
+
122
+ const xml = (text) => String(text).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;")
123
+
124
+ function timeNotes(timeline, format) {
125
+ const notes = new Map()
126
+ for (const piece of timeline.picture) {
127
+ if (piece.hold) notes.set(`${piece.clip}:hold`, { clip: piece.clip, reason: `${format} here carries no freeze frame; hold it by hand` })
128
+ else if (piece.speed.n !== piece.speed.d) notes.set(`${piece.clip}:speed`, { clip: piece.clip, reason: `${format} here carries no speed change; set ${piece.speed.n}/${piece.speed.d} by hand` })
129
+ }
130
+ return [...notes.values()]
131
+ }
132
+
133
+ /**
134
+ * @param {{ name: string, at: number }[]} [markers] chapters, written as chapter markers in the clip under each
135
+ * @returns {{ text: string, omitted: { clip: string, reason: string }[] }}
136
+ */
137
+ export function toFcpxml(project, timeline, markers = []) {
138
+ const { width, height, fps } = project.canvas
139
+ const used = handoffManifest(project, timeline)
140
+ const ref = new Map(used.map(({ asset }, i) => [asset, `r${i + 2}`]))
141
+ const resources = used.map(({ asset: id, path }) => {
142
+ const asset = assetOf(project, id)
143
+ const video = asset.kind === "video" || asset.kind === "image"
144
+ const audio = asset.facts.hasAudio !== false && asset.kind !== "image"
145
+ const media = `<media-rep kind="original-media" src="${xml(encodeURI(path))}"/>`
146
+ return ` <asset id="${ref.get(id)}" name="${xml(baseName(asset.path))}" start="0s" duration="${fractionSeconds(asset.facts.duration ?? 0)}"${video ? ' hasVideo="1" format="r1"' : ""}${audio ? ' hasAudio="1"' : ""}>${media}</asset>`
147
+ })
148
+ // Connected sound is placed on the sample; Final Cut takes edits on frames, so it moves to the nearest
149
+ const frame = (t) => snapTo(t, fps)
150
+ const connected = (item, lane, parent) => `<asset-clip ref="${ref.get(item.asset)}" lane="${lane}" offset="${fractionSeconds(frame(parent.in + item.at - parent.at))}" start="${fractionSeconds(frame(item.in))}" duration="${fractionSeconds(Math.max(frame(item.end - item.at), frameFlicks(fps) ?? 1))}" name="${xml(item.clip)}"/>`
151
+ const extras = [...timeline.overlays.filter((o) => o.asset).map((item) => [item, 1]), ...timeline.audio.filter((a) => a.role !== "dialogue").map((item) => [item, -1])]
152
+ const spine = timeline.picture.map((piece) => {
153
+ const chapters = markers
154
+ .filter((m) => m.at >= piece.at && m.at < piece.end)
155
+ .map((m) => ` <chapter-marker start="${fractionSeconds(piece.in + Math.round(((m.at - piece.at) * piece.speed.n) / piece.speed.d))}" duration="${fps.d}/${fps.n}s" value="${xml(m.name)}" posterOffset="0s"/>`)
156
+ const inner = [...extras.filter(([item]) => item.at >= piece.at && item.at < piece.end).map(([item, lane]) => ` ${connected(item, lane, piece)}`), ...chapters]
157
+ const open = `<asset-clip ref="${ref.get(piece.asset)}" offset="${fractionSeconds(piece.at)}" start="${fractionSeconds(piece.in)}" duration="${fractionSeconds(piece.end - piece.at)}" name="${xml(piece.clip)}"`
158
+ return inner.length ? ` ${open}>\n${inner.join("\n")}\n </asset-clip>` : ` ${open}/>`
159
+ })
160
+ const text = [
161
+ '<?xml version="1.0" encoding="UTF-8"?>',
162
+ "<!DOCTYPE fcpxml>",
163
+ '<fcpxml version="1.10">',
164
+ " <resources>",
165
+ ` <format id="r1" frameDuration="${fps.d}/${fps.n}s" width="${width}" height="${height}"/>`,
166
+ ...resources,
167
+ " </resources>",
168
+ " <library>",
169
+ ` <event name="${xml(project.name)}">`,
170
+ ` <project name="${xml(project.name)}">`,
171
+ ` <sequence format="r1" duration="${fractionSeconds(timeline.duration)}" tcStart="0s" tcFormat="NDF">`,
172
+ " <spine>",
173
+ ...spine,
174
+ " </spine>",
175
+ " </sequence>",
176
+ " </project>",
177
+ " </event>",
178
+ " </library>",
179
+ "</fcpxml>",
180
+ "",
181
+ ].join("\n")
182
+ return { text, omitted: [...timeNotes(timeline, "FCPXML"), ...timeline.overlays.filter((o) => !o.asset).map((o) => ({ clip: o.clip, reason: "motion and titles travel as overlay clips, not FCPXML titles" }))] }
183
+ }
184
+
185
+ // CMX 3600 record times start at the conventional 01:00:00:00
186
+ const reel = (id) => id.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 8) || "AX"
187
+ const edlTitle = (name) => name.replace(/[\r\n]+/g, " ").slice(0, 70)
188
+
189
+ /** @returns {{ text: string, omitted: { clip: string, reason: string }[] }} */
190
+ export function toEdl(project, timeline) {
191
+ const { fps } = timeline
192
+ const start = 3600 * Math.ceil(fps.n / fps.d)
193
+ const lines = [`TITLE: ${edlTitle(project.name)}`, "FCM: NON-DROP FRAME", ""]
194
+ timeline.picture.forEach((piece, i) => {
195
+ const frames = flicksToFrames(piece.end, fps) - flicksToFrames(piece.at, fps)
196
+ const source = flicksToFrames(piece.in, fps)
197
+ const record = start + flicksToFrames(piece.at, fps)
198
+ lines.push(`${String(i + 1).padStart(3, "0")} ${reel(piece.asset).padEnd(8)} AA/V C ${timecode(source, fps)} ${timecode(source + frames, fps)} ${timecode(record, fps)} ${timecode(record + frames, fps)}`)
199
+ lines.push(`* FROM CLIP NAME: ${baseName(assetOf(project, piece.asset).path)}`)
200
+ })
201
+ const extras = [...timeline.overlays, ...timeline.audio.filter((a) => a.role !== "dialogue")]
202
+ return { text: `${lines.join("\n")}\n`, omitted: [...timeNotes(timeline, "EDL"), ...extras.map((item) => ({ clip: item.clip, reason: `an EDL holds simple cuts, so this ${item.role} clip isn't in it` }))] }
203
+ }
204
+
205
+ const ordered = (timeline) => [...timeline.captions].sort((a, b) => a.at - b.at)
206
+ // A blank line would end the cue early
207
+ const cueText = (text) => text.replace(/\r\n?/g, "\n").replace(/\n{2,}/g, "\n").trim()
208
+
209
+ export function toSrt(timeline) {
210
+ return ordered(timeline)
211
+ .map((caption, i) => `${i + 1}\n${clockTime(caption.at, ",")} --> ${clockTime(caption.end, ",")}\n${cueText(caption.text)}\n`)
212
+ .join("\n")
213
+ }
214
+
215
+ export function toVtt(timeline) {
216
+ const safe = (text) => cueText(text).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
217
+ return `WEBVTT\n\n${ordered(timeline)
218
+ .map((caption) => `${clockTime(caption.at, ".")} --> ${clockTime(caption.end, ".")}\n${safe(caption.text)}\n`)
219
+ .join("\n")}`
220
+ }
@@ -0,0 +1,90 @@
1
+ // History (EDIT_ENGINE §4, DATA_MODEL §5.4): an append-only log. Undo moves HEAD and
2
+ // nothing is deleted. The caller passes the time, so this stays pure.
3
+
4
+ import { apply, opShapeErrors } from "./ops.js"
5
+ import { canonical, check, hashProject, sha256 } from "./project.js"
6
+
7
+ const ENTRY = {
8
+ id: "id",
9
+ parent: { nullable: "id" },
10
+ author: { enum: ["person", "agent", "code"] },
11
+ ops: { list: "plain" },
12
+ "promptRef?": "str",
13
+ hash: "str",
14
+ at: "str",
15
+ }
16
+
17
+ export const createLog = (project) => ({ root: project, entries: [], head: null, current: project })
18
+
19
+ const entryOf = (log, id) => {
20
+ const entry = log.entries.find((e) => e.id === id)
21
+ if (!entry) throw new RangeError(`no version "${id}"`)
22
+ return entry
23
+ }
24
+
25
+ /** The project at a version, rebuilt from the root by replay. */
26
+ export function projectAt(log, id, ctx) {
27
+ const chain = []
28
+ for (let at = id; at !== null; at = entryOf(log, at).parent) chain.unshift(entryOf(log, at))
29
+ let project = log.root
30
+ for (const entry of chain) {
31
+ const result = apply(project, entry.ops, { ...ctx, author: entry.author })
32
+ if (!result.applied) throw new RangeError(`version "${entry.id}" no longer replays: ${result.diagnostics[0].message}`)
33
+ project = result.project
34
+ }
35
+ return project
36
+ }
37
+
38
+ /** Applies operations at HEAD and appends the entry; refused operations change nothing. */
39
+ export function commit(log, { ops, author, at, promptRef }, ctx) {
40
+ const result = apply(log.current, ops, { ...ctx, author })
41
+ if (!result.applied) return { ok: false, log, project: log.current, diagnostics: result.diagnostics }
42
+ const id = sha256(canonical([log.entries.length, log.head, author, ops, at])).slice(0, 16)
43
+ const entry = { id, parent: log.head, author, ops, ...(promptRef === undefined ? {} : { promptRef }), hash: hashProject(result.project), at }
44
+ return { ok: true, log: { ...log, entries: [...log.entries, entry], head: id, current: result.project }, project: result.project, diagnostics: [] }
45
+ }
46
+
47
+ /** Moves HEAD to a version. New work from there starts a branch. */
48
+ export function checkout(log, id, ctx) {
49
+ return { ...log, head: id, current: projectAt(log, id, ctx) }
50
+ }
51
+
52
+ export function undo(log, ctx) {
53
+ return log.head === null ? log : checkout(log, entryOf(log, log.head).parent, ctx)
54
+ }
55
+
56
+ /** Re-applies every entry and compares its hash. */
57
+ export function replay(log, ctx) {
58
+ const mismatches = log.entries.filter((entry) => {
59
+ try {
60
+ return hashProject(projectAt(log, entry.id, ctx)) !== entry.hash
61
+ } catch {
62
+ return true
63
+ }
64
+ })
65
+ return { ok: mismatches.length === 0, mismatches: mismatches.map((entry) => entry.id) }
66
+ }
67
+
68
+ /** The compact Version list mirrored into the project file. */
69
+ export function versions(log) {
70
+ let next = 0
71
+ return log.entries.map(({ id, parent, author, ops, hash, at }) => {
72
+ const opsRange = [next, (next += ops.length)]
73
+ const name = ops.findLast((op) => op.op === "name_version")?.name
74
+ return { id, parent, ...(name === undefined ? {} : { name }), author, opsRange, hash, at }
75
+ })
76
+ }
77
+
78
+ /** One ops.jsonl line, validated against the same schema as live operations. */
79
+ export function parseEntry(line) {
80
+ let entry
81
+ try {
82
+ entry = JSON.parse(line)
83
+ } catch {
84
+ return { ok: false, errors: [{ path: "", reason: "this history line isn't valid JSON" }] }
85
+ }
86
+ const errors = []
87
+ check(entry, ENTRY, "", errors)
88
+ if (errors.length === 0) for (const op of entry.ops) errors.push(...opShapeErrors(op).map(({ message }) => ({ path: "ops", reason: message })))
89
+ return errors.length ? { ok: false, errors } : { ok: true, entry, errors }
90
+ }
@@ -0,0 +1,92 @@
1
+ // Layout solver (EDIT_ENGINE §5.1). Priority: never on a face; inside safe zones;
2
+ // stable; then the look's preference. Dynamic programming picks the cheapest
3
+ // sequence, so stability is decided across time, not per caption.
4
+
5
+ const ROWS = 13
6
+
7
+ /**
8
+ * Margins kept clear of each platform's own buttons and text, as shares of the frame.
9
+ * shortcut: Kriya's working margins, not figures the platforms publish; check them
10
+ * against each app's current layout before EG-8, and replace with reviewed data.
11
+ */
12
+ export const SAFE_ZONES = {
13
+ "reel-9x16": { top: 0.12, right: 0.14, bottom: 0.22, left: 0.06 },
14
+ "short-9x16": { top: 0.1, right: 0.12, bottom: 0.2, left: 0.06 },
15
+ "tiktok-9x16": { top: 0.12, right: 0.16, bottom: 0.24, left: 0.06 },
16
+ }
17
+
18
+ /** The strictest margins over a project's deliverables, in canvas pixels; {} when none applies. */
19
+ export function safeZoneFor(project) {
20
+ const { width, height } = project.canvas
21
+ const zone = {}
22
+ for (const deliverable of project.deliverables ?? []) {
23
+ const share = SAFE_ZONES[deliverable.preset]
24
+ if (!share) continue
25
+ for (const [side, value] of Object.entries(share)) zone[side] = Math.max(zone[side] ?? 0, Math.ceil(value * (side === "top" || side === "bottom" ? height : width)))
26
+ }
27
+ return zone
28
+ }
29
+
30
+ const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
31
+
32
+ function candidates(item, { canvas, safe, prefer }) {
33
+ if (item.fixed) return [{ box: item.fixed, cost: 0 }]
34
+ const { top = 0, right = 0, bottom = 0, left = 0 } = safe
35
+ const width = canvas.width - left - right
36
+ const last = canvas.height - bottom - item.h
37
+ if (item.w > width || last < top) return []
38
+ const wanted = Math.round((canvas.height * prefer) / 100)
39
+ const rows = new Set([Math.min(last, Math.max(top, wanted))])
40
+ for (let i = 0; i < ROWS; i++) rows.add(top + Math.floor(((last - top) * i) / (ROWS - 1)))
41
+ const x = left + Math.floor((width - item.w) / 2)
42
+ return [...rows]
43
+ .sort((a, b) => a - b)
44
+ .map((y) => ({ box: { x, y, w: item.w, h: item.h }, cost: Math.abs(y - wanted) }))
45
+ .filter(({ box }) => !(item.faces ?? []).some((face) => overlaps(box, face)))
46
+ }
47
+
48
+ /**
49
+ * @param {{ id: string, at: number, end: number, w: number, h: number, faces?: object[], fixed?: object }[]} items
50
+ * @param {{ canvas: { width: number, height: number }, safe?: object, prefer: number }} options prefer: percent of the height
51
+ * @returns {{ placements: Record<string, object | null>, issues: object[] }}
52
+ */
53
+ export function solveLayout(items, { canvas, safe = {}, prefer }) {
54
+ // Stability outranks preference, so one jump costs more than all preference together
55
+ const jump = canvas.height * (items.length + 1)
56
+ const issues = []
57
+ const placements = {}
58
+ const noRoom = (item) => {
59
+ placements[item.id] = null
60
+ issues.push({ code: "no_placement", clip: item.id, message: "no position clears the faces inside the safe zones" })
61
+ }
62
+ const between = (previous, a, item, b) => {
63
+ if (previous.end > item.at && overlaps(a.box, b.box)) return Infinity
64
+ return a.box.y === b.box.y ? 0 : jump + Math.abs(a.box.y - b.box.y)
65
+ }
66
+
67
+ const chain = []
68
+ for (const item of [...items].sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : 1))) {
69
+ const options = candidates(item, { canvas, safe, prefer })
70
+ const step = chain.at(-1)
71
+ const states = options.map((option) => {
72
+ if (!step) return { option, total: option.cost, from: -1 }
73
+ let best = { total: Infinity, from: -1 }
74
+ step.states.forEach((state, i) => {
75
+ const total = state.total + between(step.item, state.option, item, option)
76
+ if (total < best.total) best = { total, from: i }
77
+ })
78
+ return { option, total: best.total + option.cost, from: best.from }
79
+ })
80
+ const reachable = states.filter((state) => state.total < Infinity)
81
+ if (reachable.length === 0) noRoom(item)
82
+ else chain.push({ item, states })
83
+ }
84
+
85
+ let at = chain.at(-1)?.states.reduce((best, state, i, all) => (state.total < all[best].total ? i : best), 0)
86
+ for (let i = chain.length - 1; i >= 0; i--) {
87
+ const state = chain[i].states[at]
88
+ placements[chain[i].item.id] = state.option.box
89
+ at = state.from
90
+ }
91
+ return { placements, issues }
92
+ }
@@ -0,0 +1,115 @@
1
+ // FFmpeg arguments for the sound (EDIT_ENGINE §10, ED9): one bus, or the whole mix,
2
+ // at 48 kHz. Voice clean, music fit on downbeats, a band-split duck that leaves the
3
+ // bass and the air, levels and edge fades. Built only from typed plan data.
4
+
5
+ import { busOf, voiceClean } from "./audio.js"
6
+ import { escapeFilterValue } from "./ffmpeg.js"
7
+ import { flicksToSamples, secondsArg } from "./time.js"
8
+
9
+ export const MIX_RATE = 48_000
10
+ const EDGE_FADE = "0.015" // every boundary gets one, so no pops
11
+ export const DUCK_BANDS = [300, 3500] // Hz: only the speech band ducks (brief §E2)
12
+
13
+ const filter = (name, options) => `${name}=${Object.entries(options).map(([key, value]) => `${key}=${escapeFilterValue(value)}`).join(":")}`
14
+
15
+ function absolute(path) {
16
+ if (!path.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(path)) throw new RangeError(`an input must be an absolute path, got "${path}"`)
17
+ return path
18
+ }
19
+
20
+ const RENDERED = new Set(["level", "fade", "eq", "duck", "fit"])
21
+
22
+ /** One item's chain, from its input label to `[a<label>]`. */
23
+ function itemChain(item, input, label, duration, gain) {
24
+ const seconds = secondsArg(item.end - item.at)
25
+ const chains = []
26
+ const steps = []
27
+ let from = `[${input}:a]`
28
+ if (item.fit?.segments?.length > 1) {
29
+ // The music's path: each piece trimmed, joined by short equal-power crossfades
30
+ const parts = item.fit.segments.map((_, i) => `[f${label}_${i}]`)
31
+ chains.push(`${from}asplit=${parts.length}${parts.join("")}`)
32
+ item.fit.segments.forEach((segment, i) => chains.push(`${parts[i]}${filter("atrim", { start: secondsArg(segment.in), end: secondsArg(segment.out) })},asetpts=PTS-STARTPTS[g${label}_${i}]`))
33
+ let joined = `[g${label}_0]`
34
+ for (let i = 1; i < parts.length; i++) {
35
+ const next = `[j${label}_${i}]`
36
+ chains.push(`${joined}[g${label}_${i}]${filter("acrossfade", { d: secondsArg(item.fit.crossfade), c1: "qsin", c2: "qsin" })}${next}`)
37
+ joined = next
38
+ }
39
+ from = joined
40
+ steps.push(filter("atrim", { duration: seconds }))
41
+ } else {
42
+ const range = item.fit?.segments?.[0] ?? { in: item.in, out: item.out }
43
+ if (item.loop) steps.push("aloop=loop=-1:size=2147483647")
44
+ steps.push(filter("atrim", { start: secondsArg(range.in), ...(item.loop ? {} : { end: secondsArg(range.out) }) }), "asetpts=PTS-STARTPTS")
45
+ if (item.loop || item.fit) steps.push(filter("atrim", { duration: seconds }))
46
+ }
47
+ if (item.speed && item.speed.n !== item.speed.d) steps.push(filter("atempo", { tempo: (item.speed.n / item.speed.d).toFixed(6) }))
48
+ steps.push(filter("aresample", { sample_rate: MIX_RATE }), "aformat=channel_layouts=stereo")
49
+ const length = secondsArg(Math.min(item.end, duration) - item.at)
50
+ steps.push(filter("afade", { t: "in", d: EDGE_FADE }), filter("afade", { t: "out", st: (Number(length) - Number(EDGE_FADE)).toFixed(9), d: EDGE_FADE }))
51
+ for (const effect of item.effects) {
52
+ if (!RENDERED.has(effect.type)) throw new RangeError(`this render can't do ${effect.type} yet`)
53
+ if (effect.type === "eq") {
54
+ if (effect.preset !== "voice-clean") throw new RangeError(`this render has no "${effect.preset}" EQ`)
55
+ steps.push(...voiceClean(effect.strength))
56
+ }
57
+ if (effect.type === "level") steps.push(filter("volume", { volume: `${effect.db}dB` }))
58
+ if (effect.type === "fade" && effect.in) steps.push(filter("afade", { t: "in", d: secondsArg(effect.in) }))
59
+ if (effect.type === "fade" && effect.out) steps.push(filter("afade", { t: "out", st: secondsArg(Math.max(0, item.end - item.at - effect.out)), d: secondsArg(effect.out) }))
60
+ }
61
+ // A measured gain (SFX against the voice) unless the person set a level
62
+ if (gain !== undefined && !item.effects.some((e) => e.type === "level")) steps.push(filter("volume", { volume: `${gain.toFixed(2)}dB` }))
63
+ if (item.at > 0) steps.push(`adelay=delays=${flicksToSamples(item.at, MIX_RATE)}S:all=1`)
64
+ chains.push(`${from}${steps.join(",")}[a${label}]`)
65
+ return chains
66
+ }
67
+
68
+ /**
69
+ * The sound of a plan, or of one bus of it.
70
+ * @param {object} plan
71
+ * @param {{ input: (asset: string) => string, output: string, encoder: string[], bus?: string, envelope?: string, gains?: Record<string, number> }} io
72
+ * bus: only this bus (a stem); envelope: the duck's gain curve, mono float at 1 kHz (needed when the music ducks);
73
+ * gains: dB per asset, for music and sound effects levelled against the voice
74
+ */
75
+ export function audioArgs(plan, { input, output, encoder, bus, envelope, gains = {} }) {
76
+ const items = plan.audio.items.filter((item) => bus === undefined || busOf(item.role) === bus)
77
+ const length = secondsArg(plan.duration)
78
+ const tail = ["-t", length, ...encoder, "-y", output]
79
+ if (items.length === 0) return ["-nostdin", "-hide_banner", "-f", "lavfi", "-i", `anullsrc=r=${MIX_RATE}:cl=stereo`, ...tail]
80
+ const ducks = items.some((item) => busOf(item.role) === "music") && plan.audio.duck
81
+ if (ducks && !envelope) throw new RangeError("the duck needs its gain curve")
82
+ const inputs = items.flatMap((item) => ["-protocol_whitelist", "file,pipe", "-i", absolute(input(item.asset))])
83
+ const chains = items.flatMap((item, i) => itemChain(item, i, i, plan.duration, gains[item.asset]))
84
+ const music = items.map((item, i) => (busOf(item.role) === "music" ? `[a${i}]` : null)).filter(Boolean)
85
+ const rest = items.map((item, i) => (busOf(item.role) === "music" ? null : `[a${i}]`)).filter(Boolean)
86
+ let labels = [...rest]
87
+ if (music.length) {
88
+ let bed = music[0]
89
+ if (music.length > 1) {
90
+ chains.push(`${music.join("")}amix=inputs=${music.length}:normalize=0:duration=longest[mbed]`)
91
+ bed = "[mbed]"
92
+ }
93
+ if (ducks) {
94
+ // Only the speech band ducks: split, lower the middle by the gain curve, put back together
95
+ inputs.push("-f", "f32le", "-ar", "1000", "-ac", "1", "-i", absolute(envelope))
96
+ const e = items.length
97
+ chains.push(`[${e}:a]${filter("aresample", { sample_rate: MIX_RATE })},pan=stereo|c0=c0|c1=c0,${filter("apad", { whole_dur: length })}[env]`)
98
+ chains.push(`${bed}${filter("apad", { whole_dur: length })},${filter("acrossover", { split: DUCK_BANDS.join(" ") })}[lo][mid][hi]`)
99
+ chains.push("[mid][env]amultiply[midd]")
100
+ chains.push("[lo][midd][hi]amix=inputs=3:normalize=0:duration=first[ducked]")
101
+ bed = "[ducked]"
102
+ }
103
+ labels = [...labels, bed]
104
+ }
105
+ chains.push(`${labels.join("")}amix=inputs=${labels.length}:normalize=0:duration=longest,${filter("apad", { whole_dur: length })}[mix]`)
106
+ return ["-nostdin", "-hide_banner", ...inputs, "-filter_complex", chains.join(";"), "-map", "[mix]", "-vn", ...tail]
107
+ }
108
+
109
+ /** Stems summed into one mix, losslessly before mastering. */
110
+ export function stemsMixArgs({ stems, duration, output, encoder }) {
111
+ const length = secondsArg(duration)
112
+ if (stems.length === 1) return ["-nostdin", "-hide_banner", "-protocol_whitelist", "file,pipe", "-i", absolute(stems[0]), "-t", length, ...encoder, "-y", output]
113
+ const labels = stems.map((_, i) => `[${i}:a]`).join("")
114
+ return ["-nostdin", "-hide_banner", ...stems.flatMap((stem) => ["-protocol_whitelist", "file,pipe", "-i", absolute(stem)]), "-filter_complex", `${labels}amix=inputs=${stems.length}:normalize=0:duration=longest,${filter("apad", { whole_dur: length })}[mix]`, "-map", "[mix]", "-t", length, ...encoder, "-y", output]
115
+ }