@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,132 @@
1
+ // L5 Delivery (PERCEPTION §4): sentences, fillers, stutters, restarts, and take groups
2
+ // with a best take. Code flags only what it's sure of; the Director's take slot decides
3
+ // the rest. Thresholds are EX-11's starting points, to be tuned on real labelled clips.
4
+
5
+ export const RETAKES_VERSION = "l5-1"
6
+
7
+ const MS = 705_600
8
+ export const SENTENCE_GAP = 700 * MS // a pause this long ends a sentence without punctuation
9
+ export const FILLER_PAUSE = 150 * MS // a soft filler is cut only with a pause on both sides
10
+ export const SIMILAR = 0.65 // Jaccard on word trigrams (PERCEPTION §4)
11
+ export const LOW_CONFIDENCE = 0.5
12
+
13
+ // Sounds that are never words, and words that are fillers only when set apart by pauses
14
+ const HESITATIONS = new Set(["um", "umm", "uh", "uhh", "uhm", "er", "erm", "hmm", "mm", "ah", "eh"])
15
+ const SOFT_FILLERS = { en: ["like", "basically", "actually", "so", "right", "literally"], hi: ["matlab", "basically", "yaani"], te: ["ante", "basically"] }
16
+ const RESTARTS = ["let me try that again", "let me start again", "let me start over", "let me redo that", "one more time", "okay again", "ok again", "start over", "take two", "sorry let me", "ek minute", "phir se", "malli", "inkosari"]
17
+
18
+ const bare = (text) => text.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}' ]+/gu, "").trim()
19
+ const ends = (text) => /[.!?।]["')\]]*$/.test(text)
20
+
21
+ function trigrams(words) {
22
+ const tokens = words.map((word) => bare(word.text)).filter(Boolean)
23
+ if (tokens.length < 3) return new Set(tokens.length ? [tokens.join(" ")] : [])
24
+ return new Set(tokens.slice(2).map((_, i) => tokens.slice(i, i + 3).join(" ")))
25
+ }
26
+
27
+ const jaccard = (a, b) => {
28
+ let shared = 0
29
+ for (const item of a) if (b.has(item)) shared++
30
+ return a.size + b.size === shared ? 0 : shared / (a.size + b.size - shared)
31
+ }
32
+
33
+ /** Is the shorter run a word-for-word start of the longer? A cut-off attempt is. */
34
+ function prefixOf(short, long) {
35
+ const a = short.map((word) => bare(word.text)).filter(Boolean)
36
+ const b = long.map((word) => bare(word.text)).filter(Boolean)
37
+ return a.length >= 3 && a.length < b.length && a.every((token, i) => token === b[i])
38
+ }
39
+
40
+ /** Word flags: filler, stutter, low_confidence. Times decide a soft filler, not the word alone. */
41
+ export function flagWords(words, language = "en") {
42
+ const soft = new Set(SOFT_FILLERS[language.split("-")[0]] ?? SOFT_FILLERS.en)
43
+ return words.map((word, i) => {
44
+ const flags = []
45
+ const token = bare(word.text)
46
+ const before = i === 0 ? Infinity : word.start - words[i - 1].end
47
+ const after = i === words.length - 1 ? Infinity : words[i + 1].start - word.end
48
+ // Punctuation marks a pause the recogniser heard, even with tight times
49
+ const setApart = (before >= FILLER_PAUSE || ends(words[i - 1]?.text ?? ".") || /,$/.test(words[i - 1]?.text ?? "")) && (after >= FILLER_PAUSE || /[,.!?]$/.test(word.text))
50
+ if (HESITATIONS.has(token) || (soft.has(token) && setApart)) flags.push("filler")
51
+ const next = words[i + 1]
52
+ if (next && token && (bare(next.text) === token || (word.text.endsWith("-") && bare(next.text).startsWith(token)))) flags.push("stutter")
53
+ if (typeof word.conf === "number" && word.conf < LOW_CONFIDENCE) flags.push("low_confidence")
54
+ return flags
55
+ })
56
+ }
57
+
58
+ /** Sentences: punctuation, or a long pause. @returns {{ first: number, last: number }[]} word positions */
59
+ export function sentencesOf(words) {
60
+ const sentences = []
61
+ let first = 0
62
+ words.forEach((word, i) => {
63
+ const next = words[i + 1]
64
+ if (!next || ends(word.text) || next.start - word.end >= SENTENCE_GAP) {
65
+ sentences.push({ first, last: i })
66
+ first = i + 1
67
+ }
68
+ })
69
+ return sentences
70
+ }
71
+
72
+ const isRestart = (words) => {
73
+ const text = ` ${words.map((word) => bare(word.text)).join(" ")} `
74
+ return RESTARTS.some((phrase) => text.includes(` ${phrase} `))
75
+ }
76
+
77
+ /**
78
+ * The whole layer, on plain words with times in flicks.
79
+ * @returns {{ flags: string[][], sentences: { first: number, last: number, start: number, end: number, group: number | null, score: number }[], takes: { group: number, sentence: number, rank: number, signals: object }[] }}
80
+ */
81
+ export function analyseDelivery(words, { language = "en" } = {}) {
82
+ const flags = flagWords(words, language)
83
+ const sentences = sentencesOf(words).map((s) => ({ ...s, start: words[s.first].start, end: words[s.last].end, group: null, score: 0 }))
84
+ const span = (s) => words.slice(s.first, s.last + 1)
85
+ // Attempts are compared on what was meant: fillers would break the trigrams
86
+ const content = (s) => span(s).filter((_, k) => !flags[s.first + k].includes("filler"))
87
+
88
+ // A restart phrase belongs to no take; it marks the attempt before it as one
89
+ const restart = sentences.map((s) => isRestart(span(s)))
90
+ for (const [i, s] of sentences.entries()) if (restart[i]) for (let w = s.first; w <= s.last; w++) flags[w].push("restart")
91
+
92
+ // Neighbouring attempts at one line, skipping restart phrases between them
93
+ let groups = 0
94
+ let previous = null
95
+ for (const [i, s] of sentences.entries()) {
96
+ if (restart[i]) continue
97
+ if (previous !== null) {
98
+ const a = content(sentences[previous])
99
+ const b = content(s)
100
+ const similar = jaccard(trigrams(a), trigrams(b)) >= SIMILAR || prefixOf(a, b) || prefixOf(b, a)
101
+ const marked = sentences.slice(previous + 1, i).some((_, k) => restart[previous + 1 + k])
102
+ if (similar || (marked && jaccard(trigrams(a.slice(0, 3)), trigrams(b.slice(0, 3))) > 0)) {
103
+ sentences[previous].group ??= groups++
104
+ s.group = sentences[previous].group
105
+ }
106
+ }
107
+ previous = i
108
+ }
109
+
110
+ const takes = []
111
+ for (let group = 0; group < groups; group++) {
112
+ const members = sentences.map((s, i) => ({ s, i })).filter(({ s }) => s.group === group)
113
+ const longest = Math.max(...members.map(({ s }) => content(s).length))
114
+ for (const [order, { s, i }] of members.entries()) {
115
+ const own = span(s)
116
+ const fillers = own.filter((_, k) => flags[s.first + k].some((flag) => flag === "filler" || flag === "stutter")).length
117
+ const complete = ends(own.at(-1).text) && content(s).length >= longest * 0.8 && !members.slice(order + 1).some(({ s: later }) => prefixOf(own, span(later)))
118
+ const followedByRestart = restart[i + 1] === true
119
+ const signals = { fluency: Math.round((1 - fillers / own.length) * 100) / 100, complete, followedByRestart, last: order === members.length - 1 }
120
+ // The last clean take usually wins (PERCEPTION §4)
121
+ s.score = Math.round((signals.fluency + (complete ? 1 : 0) - (followedByRestart ? 1 : 0) + (signals.last ? 0.1 : 0)) * 100) / 100
122
+ takes.push({ group, sentence: i, rank: 0, signals })
123
+ }
124
+ const ranked = takes.filter((t) => t.group === group).sort((a, b) => sentences[b.sentence].score - sentences[a.sentence].score || b.sentence - a.sentence)
125
+ ranked.forEach((take, rank) => (take.rank = rank + 1))
126
+ }
127
+ // An attempt abandoned for a different line is still a bad take
128
+ sentences.forEach((s, i) => {
129
+ if (s.group === null) s.score = restart[i] || restart[i + 1] ? 0 : 1
130
+ })
131
+ return { flags, sentences, takes }
132
+ }
@@ -0,0 +1,99 @@
1
+ // L9 Screen (PERCEPTION §2): cursor track and where the screen changes, by frame
2
+ // difference on a small grey copy of the picture. Own code, no OpenCV: a grid of cells
3
+ // marks what changed; joined cells make regions; small changes that revert are the
4
+ // cursor; the largest change that isn't its trail is the action. Times are flicks.
5
+
6
+ import { runTool } from "../../engine/tool.js"
7
+
8
+ export const SCREEN_VERSION = "l9-1"
9
+ export const SCREEN = { fps: 5, width: 160, height: 90, cell: 5, threshold: 24, minPixels: 3, cursorCells: 4, lag: 5 }
10
+ const FLICKS = 705_600_000
11
+
12
+ export const screenArgs = (source, { fps, width, height } = SCREEN) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", source, "-an", "-sn", "-dn", "-vf", `fps=${fps},scale=${width}:${height},format=gray`, "-f", "rawvideo", "-pix_fmt", "gray", "-"]
13
+
14
+ /** Reads the grey frames of `source`. @returns {Promise<Buffer>} */
15
+ export async function readScreenFrames(source, { run = runTool, signal } = {}) {
16
+ const chunks = []
17
+ await run("ffmpeg", screenArgs(source), { onStdout: (chunk) => chunks.push(chunk), signal, stallMs: 60_000 })
18
+ return Buffer.concat(chunks)
19
+ }
20
+
21
+ /** Joined changed cells (4-neighbour), each as a cell count and a bounding box in cells. */
22
+ function regions(changed, cols, rows) {
23
+ const seen = new Uint8Array(changed.length)
24
+ const found = []
25
+ for (let start = 0; start < changed.length; start++) {
26
+ if (!changed[start] || seen[start]) continue
27
+ const stack = [start]
28
+ seen[start] = 1
29
+ const box = { x0: cols, y0: rows, x1: -1, y1: -1, cells: 0 }
30
+ while (stack.length) {
31
+ const i = stack.pop()
32
+ const [x, y] = [i % cols, Math.floor(i / cols)]
33
+ Object.assign(box, { x0: Math.min(box.x0, x), y0: Math.min(box.y0, y), x1: Math.max(box.x1, x), y1: Math.max(box.y1, y), cells: box.cells + 1 })
34
+ for (const [nx, ny] of [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]]) {
35
+ const j = ny * cols + nx
36
+ if (nx >= 0 && ny >= 0 && nx < cols && ny < rows && changed[j] && !seen[j]) {
37
+ seen[j] = 1
38
+ stack.push(j)
39
+ }
40
+ }
41
+ }
42
+ found.push(box)
43
+ }
44
+ return found
45
+ }
46
+
47
+ /**
48
+ * One sample per frame after the first. A cursor gives back what it covered: pixels it
49
+ * entered one frame return the next, so a sample whose change reverts (or the sample
50
+ * just before one) is the cursor's. Content stays: a new character never reverts. The
51
+ * action is what changed since `lag` frames before (a second), minus the cells the
52
+ * cursor touched meanwhile: typing grows a few pixels a frame and adds up.
53
+ * shortcut: a moving cursor shows as two blobs (where it was, where it is) and the track takes their middle; a pointer-shape match replaces it when L9 grows one
54
+ * @param {Buffer} frames grey frames of `width` × `height`
55
+ * @param {{ sourceWidth: number, sourceHeight: number, start?: number }} source boxes come back in source pixels
56
+ * @returns {{ t: number, change: { x: number, y: number, w: number, h: number } | null, cursor: { x: number, y: number } | null }[]}
57
+ */
58
+ export function screenTrack(frames, { sourceWidth, sourceHeight, start = 0 }, options = SCREEN) {
59
+ const { fps, width, height, cell, threshold, minPixels, cursorCells, lag } = options
60
+ const size = width * height
61
+ const count = Math.floor(frames.length / size)
62
+ const [cols, rows] = [Math.ceil(width / cell), Math.ceil(height / cell)]
63
+ const [sx, sy] = [sourceWidth / width, sourceHeight / height]
64
+ const toSource = (b) => ({ x: Math.round(b.x0 * cell * sx), y: Math.round(b.y0 * cell * sy), w: Math.round(Math.min(width - b.x0 * cell, (b.x1 - b.x0 + 1) * cell) * sx), h: Math.round(Math.min(height - b.y0 * cell, (b.y1 - b.y0 + 1) * cell) * sy) })
65
+ const differs = (a, b, i) => Math.abs(frames[a * size + i] - frames[b * size + i]) > threshold
66
+ const changedCells = (a, b) => {
67
+ const counts = new Uint16Array(cols * rows)
68
+ for (let i = 0; i < size; i++) if (differs(a, b, i)) counts[Math.floor(Math.floor(i / width) / cell) * cols + Math.floor((i % width) / cell)]++
69
+ return counts.map((n) => (n >= minPixels ? 1 : 0))
70
+ }
71
+ const touches = (a, b) => a.x0 <= b.x1 + 1 && b.x0 <= a.x1 + 1 && a.y0 <= b.y1 + 1 && b.y0 <= a.y1 + 1
72
+
73
+ // Pass 1: each sample's small blobs, and whether anything that changed last frame went back
74
+ const blobs = [null]
75
+ const reverts = [false]
76
+ for (let f = 1; f < count; f++) {
77
+ blobs.push(regions(changedCells(f - 1, f), cols, rows).filter((r) => r.cells <= cursorCells))
78
+ let back = 0
79
+ if (f >= 2) for (let i = 0; i < size && back < minPixels; i++) if (differs(f - 1, f - 2, i) && !differs(f, f - 2, i)) back++
80
+ reverts.push(back >= minPixels)
81
+ }
82
+ const isCursor = (f) => blobs[f].length > 0 && (reverts[f] || (f + 1 < count && reverts[f + 1] && blobs[f].some((r) => blobs[f + 1].some((b) => touches(r, b)))))
83
+
84
+ // Pass 2: the cursor's trail, and the action since a second ago without it
85
+ const trails = []
86
+ const samples = []
87
+ for (let f = 1; f < count; f++) {
88
+ const small = isCursor(f) ? blobs[f] : []
89
+ const trail = new Set()
90
+ for (const r of small) for (let y = r.y0 - 1; y <= r.y1 + 1; y++) for (let x = r.x0 - 1; x <= r.x1 + 1; x++) if (x >= 0 && y >= 0 && x < cols && y < rows) trail.add(y * cols + x)
91
+ trails.push(trail)
92
+ const crossed = new Set(trails.slice(-lag).flatMap((t) => [...t]))
93
+ const since = changedCells(Math.max(0, f - lag), f).map((v, i) => (v && !crossed.has(i) ? 1 : 0))
94
+ const action = regions(since, cols, rows).sort((p, q) => q.cells - p.cells)[0]
95
+ const cursor = small.length ? toSource({ x0: Math.min(...small.map((r) => r.x0)), y0: Math.min(...small.map((r) => r.y0)), x1: Math.max(...small.map((r) => r.x1)), y1: Math.max(...small.map((r) => r.y1)) }) : null
96
+ samples.push({ t: start + Math.round((f * FLICKS) / fps), change: action ? toSource(action) : null, cursor: cursor ? { x: cursor.x + Math.round(cursor.w / 2), y: cursor.y + Math.round(cursor.h / 2) } : null })
97
+ }
98
+ return samples
99
+ }
@@ -0,0 +1,29 @@
1
+ // L6 Shots: hard cuts from FFmpeg's scene detector (`scdet`), on a small copy of
2
+ // the picture. Gradual transitions (fades, dissolves) need TransNetV2; until then a
3
+ // shot list has hard cuts only, and says so.
4
+
5
+ import { metadataFrames, ptsFlicks } from "./meta.js"
6
+
7
+ export const SHOTS_VERSION = "l6-1"
8
+ export const CUT_SCORE = 10 // scdet's own scale, 0–100; its documented default
9
+ const MICROS = 1_000_000
10
+
11
+ export const shotArgs = (source) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", source, "-an", "-sn", "-dn", "-vf", `scale=320:-2,settb=AVTB,scdet=threshold=${CUT_SCORE}:sc_pass=1,metadata=mode=print:file=-`, "-f", "null", "-"]
12
+
13
+ /** Cut times → shots covering the whole asset. @returns {{ start: number, end: number, kind: string, score: number | null }[]} */
14
+ export function readShots(text, duration) {
15
+ const cuts = metadataFrames(text)
16
+ .map(({ pts, values }) => ({ t: ptsFlicks(pts, MICROS), score: Number(values["lavfi.scd.score"]) }))
17
+ .filter(({ t }) => t > 0 && t < duration)
18
+ const shots = []
19
+ let start = 0
20
+ let score = null
21
+ for (const cut of cuts) {
22
+ if (cut.t <= start) continue
23
+ shots.push({ start, end: cut.t, kind: "cut", score })
24
+ start = cut.t
25
+ score = cut.score
26
+ }
27
+ if (duration > start) shots.push({ start, end: duration, kind: "cut", score })
28
+ return shots
29
+ }
@@ -0,0 +1,42 @@
1
+ // L1 Sound map: a loudness curve (EBU R128 momentary), a peak envelope and silences,
2
+ // at 100 ms, from one FFmpeg pass. Voice activity (silero-vad) is a later layer.
3
+
4
+ import { decimalFlicks, finite, metadataFrames, ptsFlicks } from "./meta.js"
5
+
6
+ export const SOUND_VERSION = "l1-1"
7
+ const RATE = 48_000
8
+ export const STEP = 70_560_000 // 100 ms in flicks
9
+ export const SILENCE_DB = -40
10
+ const SILENCE_SECONDS = 0.3
11
+
12
+ export const soundArgs = (source) => [
13
+ "-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", source, "-vn", "-sn", "-dn",
14
+ "-af", `aresample=${RATE},asetnsamples=n=${RATE / 10}:p=0,asettb=1/${RATE},ebur128=metadata=1,silencedetect=n=${SILENCE_DB}dB:d=${SILENCE_SECONDS},astats=metadata=1:reset=1:measure_overall=Peak_level:measure_perchannel=none,ametadata=mode=print:file=-`,
15
+ "-f", "null", "-",
16
+ ]
17
+
18
+ const round1 = (value) => (value === null ? null : Math.round(value * 10) / 10)
19
+
20
+ /** @returns {{ data: { step: number, loudness: (number|null)[], peaks: (number|null)[], integrated: number|null }, silences: { start: number, end: number }[] }} */
21
+ export function readSound(text, duration) {
22
+ const frames = metadataFrames(text)
23
+ const loudness = []
24
+ const peaks = []
25
+ const silences = []
26
+ let integrated = null
27
+ let open = null
28
+ for (const { values } of frames) {
29
+ const m = finite(values["lavfi.r128.M"])
30
+ loudness.push(m === null || m < -70 ? null : round1(m)) // below R128's absolute gate is silence
31
+ peaks.push(round1(finite(values["lavfi.astats.Overall.Peak_level"])))
32
+ integrated = finite(values["lavfi.r128.I"]) ?? integrated
33
+ // silencedetect's times are its own decimal seconds, to the microsecond
34
+ if (values["lavfi.silence_start"] !== undefined) open = Math.max(0, decimalFlicks(values["lavfi.silence_start"]))
35
+ if (values["lavfi.silence_end"] !== undefined && open !== null) {
36
+ silences.push({ start: open, end: decimalFlicks(values["lavfi.silence_end"]) })
37
+ open = null
38
+ }
39
+ }
40
+ if (open !== null) silences.push({ start: open, end: duration ?? (frames.length ? ptsFlicks(frames.at(-1).pts, RATE) + STEP : open) })
41
+ return { data: { step: STEP, loudness, peaks, integrated: integrated !== null && integrated > -70 ? round1(integrated) : null }, silences }
42
+ }
@@ -0,0 +1,64 @@
1
+ // L2 Words: a word-level transcript, kept verbatim (ET-HR-08), from the Media
2
+ // Runtime's Whisper: mlx-whisper on Apple silicon, faster-whisper elsewhere (EX-04).
3
+ // The language is the person's setting, never detected (PERCEPTION §5). The model
4
+ // runs offline: weights come with the runtime, or the layer is unavailable.
5
+
6
+ import { existsSync } from "node:fs"
7
+ import { join } from "node:path"
8
+
9
+ import { decimalFlicks } from "./meta.js"
10
+
11
+ export const WORDS_VERSION = "l2-1"
12
+ export const MODEL = "whisper-large-v3-turbo"
13
+
14
+ // Prints one JSON line per word; times as fixed decimals, so no float crosses into Node
15
+ const SCRIPT = `
16
+ import json, sys
17
+ audio, engine, model, language = sys.argv[1:5]
18
+ def say(text, start, end, p):
19
+ print(json.dumps({"w": text, "s": f"{start:.3f}", "e": f"{end:.3f}", "p": round(float(p), 3)}), flush=True)
20
+ if engine == "mlx":
21
+ import mlx_whisper
22
+ result = mlx_whisper.transcribe(audio, path_or_hf_repo=model, language=language, word_timestamps=True, condition_on_previous_text=False)
23
+ for segment in result["segments"]:
24
+ for w in segment.get("words", []):
25
+ say(w["word"], w["start"], w["end"], w.get("probability", 0))
26
+ else:
27
+ from faster_whisper import WhisperModel
28
+ segments, _ = WhisperModel(model).transcribe(audio, language=language, word_timestamps=True, condition_on_previous_text=False)
29
+ for segment in segments:
30
+ for w in segment.words or []:
31
+ say(w.word, w.start, w.end, w.probability)
32
+ `
33
+
34
+ /** 16 kHz mono PCM for the recogniser, decoded by our FFmpeg, not the model's. */
35
+ export const speechArgs = (source, output) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", source, "-vn", "-sn", "-dn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-y", output]
36
+
37
+ /**
38
+ * Where the runtime's recogniser is, or why there isn't one.
39
+ * @param {{ dir: string } | null} runtime from activeRuntime()
40
+ */
41
+ export function recogniser(runtime, platform = `${process.platform}-${process.arch}`) {
42
+ if (!runtime) return { missing: "Speech-to-text needs the Media Runtime. Run kriya edit setup." }
43
+ const python = join(runtime.dir, "python", "bin", "python")
44
+ const model = join(runtime.dir, "models", MODEL)
45
+ if (!existsSync(python)) return { missing: "The Media Runtime has no Python environment. Run kriya edit setup again." }
46
+ if (!existsSync(model)) return { missing: "The speech model isn't installed with this Media Runtime yet." }
47
+ return { python, model, engine: platform === "darwin-arm64" ? "mlx" : "faster" }
48
+ }
49
+
50
+ export const transcribeArgs = ({ engine, model }, audio, language) => ["-I", "-c", SCRIPT, audio, engine, model, language]
51
+
52
+ /** The recogniser's lines → words, text kept exactly as heard; only the surrounding space goes. */
53
+ export function readWords(text) {
54
+ const words = []
55
+ for (const line of text.split("\n")) {
56
+ if (!line.trim()) continue
57
+ const { w, s, e, p } = JSON.parse(line)
58
+ const body = String(w).trim()
59
+ if (!body) continue
60
+ const start = decimalFlicks(s)
61
+ words.push({ text: body, start, end: Math.max(start, decimalFlicks(e)), conf: typeof p === "number" ? p : null })
62
+ }
63
+ return words
64
+ }
@@ -0,0 +1,248 @@
1
+ // The story tree (PERCEPTION_AND_INDEX §8): sentence → beat → scene → act, so a long
2
+ // recording is read once and the Director descends only where it needs to. Built by
3
+ // code with no model call: beats split at pauses, speaker changes and a size cap;
4
+ // scenes at topic shifts (TextTiling depth over sentence vectors, plus long pauses);
5
+ // acts by where scenes sit in the running time. Every summary is the transcript's own
6
+ // sentences, by id, so a claim can be traced to its words (ET-IDX-06).
7
+ // Beat summaries are cached by their content: an unchanged chunk is never read again.
8
+
9
+ import { createHash } from "node:crypto"
10
+
11
+ import { openingStrength } from "../recipes/short-from-long.js"
12
+
13
+ const FLICKS = 705_600_000
14
+ export const STORY_VERSION = "story-1"
15
+ export const STORY = {
16
+ pause: 2 * FLICKS, // a pause this long ends a beat
17
+ longPause: 4 * FLICKS, // and this long counts toward a scene break
18
+ beatMax: 8, // sentences
19
+ window: 6, // sentences either side when comparing topics
20
+ depth: 0.25, // TextTiling depth a scene break needs
21
+ sceneMin: 45 * FLICKS,
22
+ quotes: 3,
23
+ }
24
+
25
+ const DIMS = 256
26
+ const STOPWORDS = new Set("that this with have from they what there about which would their just like more than then when your were been into only also very here some them will because really thing things know think going want said does make made well even much many most other over such these those where while after before every could should being".split(" "))
27
+
28
+ const sha = (text) => createHash("sha256").update(text).digest("hex")
29
+ const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0)
30
+
31
+ function centroid(vectors) {
32
+ const c = new Array(DIMS).fill(0)
33
+ for (const v of vectors) for (let i = 0; i < DIMS; i++) c[i] += v[i]
34
+ const norm = Math.hypot(...c)
35
+ return norm ? c.map((x) => x / norm) : c
36
+ }
37
+
38
+ const wordsOf = (text) => (text.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? []).filter((w) => w.length >= 4 && !STOPWORDS.has(w))
39
+ const stem = (word) => word.replace(/(ing|ed|es|s)$/, "")
40
+
41
+ /**
42
+ * Sentence vectors: content words hashed into 256 dims, weighted by how rare each is in
43
+ * this recording (idf), so the speaker's habits ("the real reason") don't read as a topic.
44
+ * shortcut: lexical, so synonyms don't meet; L11's embeddings replace it when that layer is built
45
+ */
46
+ function vectorsOf(texts) {
47
+ const bags = texts.map((t) => wordsOf(t).map(stem))
48
+ const df = new Map()
49
+ for (const bag of bags) for (const w of new Set(bag)) df.set(w, (df.get(w) ?? 0) + 1)
50
+ return bags.map((bag) => {
51
+ const v = new Array(DIMS).fill(0)
52
+ for (const w of bag) {
53
+ let h = 2166136261
54
+ for (const c of w) h = Math.imul(h ^ c.charCodeAt(0), 16777619)
55
+ v[(h >>> 0) % DIMS] += Math.log(texts.length / df.get(w))
56
+ }
57
+ const norm = Math.hypot(...v)
58
+ return norm ? v.map((x) => x / norm) : v
59
+ })
60
+ }
61
+
62
+ const lineOf = (text) => ({ words: text.split(/\s+/).filter(Boolean).map((t) => ({ text: t })) })
63
+ const finished = (text) => /[.!?]["')]?$/.test(text.trim())
64
+
65
+ /** The asset's sentences in time order, with their text and speaker. */
66
+ export function sentencesOf(index, asset) {
67
+ const words = index.words.filter((w) => w.asset === asset)
68
+ const at = new Map(words.map((w, i) => [w.id, i]))
69
+ return index.sentences
70
+ .filter((s) => s.asset === asset && at.has(s.firstWord) && at.has(s.lastWord))
71
+ .sort((a, b) => a.start - b.start)
72
+ .map((s) => {
73
+ const list = words.slice(at.get(s.firstWord), at.get(s.lastWord) + 1)
74
+ return { id: s.id, start: s.start, end: s.end, firstWord: s.firstWord, text: list.map((w) => w.text).join(" "), speaker: s.speaker ?? list[0]?.speaker ?? null }
75
+ })
76
+ }
77
+
78
+ function beatsOf(sentences, rules) {
79
+ const beats = []
80
+ let current = []
81
+ sentences.forEach((s, i) => {
82
+ const prev = sentences[i - 1]
83
+ if (prev && (s.start - prev.end >= rules.pause || s.speaker !== prev.speaker || current.length >= rules.beatMax)) {
84
+ beats.push(current)
85
+ current = []
86
+ }
87
+ current.push(s)
88
+ })
89
+ if (current.length) beats.push(current)
90
+ return beats
91
+ }
92
+
93
+ /** What a chunk says, from its own sentences: content-word counts and its quotable lines. */
94
+ function readChunk(sentences) {
95
+ const terms = {}
96
+ for (const s of sentences) for (const word of wordsOf(s.text)) terms[word] = (terms[word] ?? 0) + 1
97
+ const quotable = sentences
98
+ .map((s) => ({ sentence: s.id, strength: openingStrength(lineOf(s.text)), finished: finished(s.text) }))
99
+ .filter((q) => q.strength >= 0.75 && q.finished)
100
+ .map(({ sentence, strength }) => ({ sentence, standsAlone: strength > 0 }))
101
+ return { terms, quotable }
102
+ }
103
+
104
+ // TextTiling depth: how far the similarity at a boundary sits below the peaks either side
105
+ function depths(sims) {
106
+ return sims.map((sim, i) => {
107
+ let left = sim
108
+ for (let j = i - 1; j >= 0 && sims[j] >= left; j--) left = sims[j]
109
+ let right = sim
110
+ for (let j = i + 1; j < sims.length && sims[j] >= right; j++) right = sims[j]
111
+ return left - sim + (right - sim)
112
+ })
113
+ }
114
+
115
+ const titleCase = (word) => word.charAt(0).toUpperCase() + word.slice(1)
116
+
117
+ /**
118
+ * @param {{ words: object[], sentences: object[] }} index
119
+ * @param {string} asset
120
+ * @param {{ cache?: { get(key: string): any, set(key: string, value: any): any }, rules?: typeof STORY }} [options]
121
+ * @returns {{ version: string, asset: string, key: string, acts: object[], scenes: object[], beats: object[], stats: { sentences: number, computed: number, cached: number } }}
122
+ */
123
+ export function storyTree(index, asset, { cache = new Map(), rules = STORY } = {}) {
124
+ const sentences = sentencesOf(index, asset)
125
+ const vectors = vectorsOf(sentences.map((s) => s.text))
126
+ const position = new Map(sentences.map((s, i) => [s.id, i]))
127
+ const stats = { sentences: sentences.length, computed: 0, cached: 0 }
128
+
129
+ // Scene breaks fall between sentences where the topic shifts
130
+ const sims = sentences.slice(1).map((_, i) => dot(centroid(vectors.slice(Math.max(0, i + 1 - rules.window), i + 1)), centroid(vectors.slice(i + 1, i + 1 + rules.window))))
131
+ const pauseAt = (i) => (sentences[i + 1].start - sentences[i].end >= rules.longPause ? 0.1 : 0)
132
+ const scores = depths(sims).map((d, i) => d + pauseAt(i))
133
+ // A valley can be flat; depth favours its edge, so a break slides to the lowest point within two sentences
134
+ const floorNear = (i) => {
135
+ let best = i
136
+ for (let j = Math.max(0, i - 2); j <= Math.min(sims.length - 1, i + 2); j++) if (sims[j] - pauseAt(j) < sims[best] - pauseAt(best)) best = j
137
+ return best
138
+ }
139
+ const cuts = []
140
+ const lengthOk = (from, to) => sentences[to - 1].end - sentences[from].start >= rules.sceneMin
141
+ for (const i of scores.map((_, i) => i).sort((a, b) => scores[b] - scores[a] || a - b)) {
142
+ if (scores[i] < rules.depth) break
143
+ const at = floorNear(i) + 1 // the first sentence of the new scene
144
+ if (cuts.includes(at)) continue
145
+ const left = Math.max(0, ...cuts.filter((c) => c < at))
146
+ const right = Math.min(sentences.length, ...cuts.filter((c) => c > at))
147
+ if (lengthOk(left, at) && lengthOk(at, right)) cuts.push(at)
148
+ }
149
+ const edges = [0, ...cuts.sort((a, b) => a - b), sentences.length]
150
+
151
+ // Beats inside each scene, never across a break
152
+ const beats = []
153
+ const groups = edges.slice(1).map((end, i) =>
154
+ beatsOf(sentences.slice(edges[i], end), rules).map((list) => {
155
+ const key = sha(`${STORY_VERSION}\n${list.map((s) => `${s.id}\t${s.text}`).join("\n")}`)
156
+ let read = cache.get(key)
157
+ if (read) stats.cached++
158
+ else {
159
+ read = readChunk(list)
160
+ cache.set(key, read)
161
+ stats.computed++
162
+ }
163
+ const beat = { id: `${asset}:b${beats.length}`, level: "beat", key, sentences: list.map((s) => s.id), from: list[0].id, to: list.at(-1).id, start: list[0].start, end: list.at(-1).end, ...read }
164
+ beats.push(beat)
165
+ return beat
166
+ }),
167
+ )
168
+
169
+ // A scene's title: its two most distinctive words against the other scenes (tf-idf)
170
+ const termsOf = (group) => group.reduce((all, b) => (Object.entries(b.terms).forEach(([w, n]) => (all[w] = (all[w] ?? 0) + n)), all), {})
171
+ const sceneTerms = groups.map(termsOf)
172
+ const seenIn = (word) => sceneTerms.filter((t) => t[word]).length
173
+ const scenes = groups.map((group, n) => {
174
+ const terms = sceneTerms[n]
175
+ const topics = Object.keys(terms)
176
+ .map((w) => [w, terms[w] * Math.log((1 + groups.length) / seenIn(w))])
177
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
178
+ .slice(0, 3)
179
+ .map(([w]) => w)
180
+ const ids = group.flatMap((b) => b.sentences)
181
+ const centre = centroid(ids.map((id) => vectors[position.get(id)]))
182
+ const central = ids.slice(1).sort((a, b) => dot(vectors[position.get(b)], centre) - dot(vectors[position.get(a)], centre) || position.get(a) - position.get(b))[0]
183
+ const summary = [ids[0], ...(central ? [central] : [])].map((id) => ({ sentence: id, text: sentences[position.get(id)].text }))
184
+ return {
185
+ id: `${asset}:sc${n}`,
186
+ level: "scene",
187
+ title: topics.slice(0, 2).map(titleCase).join(" and ") || `Part ${n + 1}`,
188
+ topics,
189
+ from: ids[0],
190
+ to: ids.at(-1),
191
+ start: group[0].start,
192
+ end: group.at(-1).end,
193
+ summary,
194
+ quotable: group.flatMap((b) => b.quotable).slice(0, rules.quotes),
195
+ children: group.map((b) => b.id),
196
+ }
197
+ })
198
+
199
+ // Acts: opening, body and close by where each scene's middle falls
200
+ const [first, last] = [sentences[0]?.start ?? 0, sentences.at(-1)?.end ?? 0]
201
+ const actOf = (scene) => {
202
+ const middle = ((scene.start + scene.end) / 2 - first) / Math.max(1, last - first)
203
+ return middle < 0.25 ? 0 : middle > 0.75 ? 2 : 1
204
+ }
205
+ const acts = ["Opening", "Body", "Close"]
206
+ .map((title, n) => ({ title, scenes: scenes.filter((s) => actOf(s) === n) }))
207
+ .filter((a) => a.scenes.length)
208
+ .map(({ title, scenes: list }, n) => ({ id: `${asset}:act${n}`, level: "act", title, from: list[0].from, to: list.at(-1).to, start: list[0].start, end: list.at(-1).end, topics: [...new Set(list.flatMap((s) => s.topics))].slice(0, 5), summary: list.map((s) => s.summary[0]), children: list.map((s) => s.id) }))
209
+
210
+ const strip = ({ terms: _, ...beat }) => beat
211
+ return { version: STORY_VERSION, asset, key: sha(beats.map((b) => b.key).join("")), acts, scenes, beats: beats.map(strip), stats }
212
+ }
213
+
214
+ /** YouTube's chapter time: m:ss under an hour (two-digit minutes, as "00:00"), h:mm:ss over. */
215
+ export function chapterTime(t) {
216
+ const s = Math.floor(t / FLICKS)
217
+ const [h, m, sec] = [Math.floor(s / 3600), Math.floor((s % 3600) / 60), s % 60]
218
+ const two = (n) => String(n).padStart(2, "0")
219
+ return h ? `${h}:${two(m)}:${two(sec)}` : `${two(m)}:${two(sec)}`
220
+ }
221
+
222
+ /**
223
+ * Chapters from the scenes, on the cut's own timeline. `placeOf(sentenceId)` gives where
224
+ * a sentence starts on the timeline, or null if it was cut. YouTube's rules: the first at
225
+ * 00:00, at least three, each at least ten seconds; a short one folds into the one before.
226
+ * @returns {{ chapters: { at: number, title: string, scene: string }[], note?: string }}
227
+ */
228
+ export function chapters(tree, placeOf, { duration, min = 3, minLength = 10 * FLICKS } = {}) {
229
+ const found = []
230
+ for (const scene of tree.scenes) {
231
+ const at = scene.children
232
+ .flatMap((id) => tree.beats.find((b) => b.id === id).sentences)
233
+ .map(placeOf)
234
+ .find((t) => t !== null && t !== undefined)
235
+ if (at !== undefined && (!found.length || at > found.at(-1).at)) found.push({ at, title: scene.title, scene: scene.id })
236
+ }
237
+ if (!found.length) return { chapters: [], note: "No scene is in the cut, so there are no chapters." }
238
+ found[0] = { ...found[0], at: 0, title: "Intro" }
239
+ const kept = []
240
+ // A short one, or one named like the one before, folds into it
241
+ for (const c of found) if (!kept.length || (c.at - kept.at(-1).at >= minLength && c.title !== kept.at(-1).title)) kept.push(c)
242
+ if (duration !== undefined && kept.length > 1 && duration - kept.at(-1).at < minLength) kept.pop()
243
+ if (kept.length < min) return { chapters: [], note: `Only ${kept.length} chapter${kept.length === 1 ? "" : "s"} of ten seconds or more; YouTube needs ${min}, so none are written.` }
244
+ return { chapters: kept }
245
+ }
246
+
247
+ /** The list a person pastes into a YouTube description. */
248
+ export const chapterList = (list) => list.map((c) => `${chapterTime(c.at)} ${c.title}`).join("\n")