@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,417 @@
1
+ // A job from Kriya, in the Host (TAVI_INTEGRATION §4). The daemon only hands it over
2
+ // (EH-02); from then on this file reports it, so a closed harness or a restarted daemon
3
+ // doesn't matter. Plain code with no agent loop. What leaves for Kriya is of a fixed
4
+ // shape: a stage, a percent, gate ids and a reason code. No transcript and no file
5
+ // names (CC-D8). The one file that leaves is a preview of this job's own output.
6
+
7
+ import { createHash } from "node:crypto"
8
+ import { createReadStream, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
9
+ import { basename, dirname, extname, join } from "node:path"
10
+ import { Readable } from "node:stream"
11
+
12
+ import { call, KriyaError } from "../../api.js"
13
+ import { readDevice } from "../../store.js"
14
+ import { clipArgs, previewArgs } from "../core/ffmpeg.js"
15
+ import { encoderFor } from "../engine/capabilities.js"
16
+ import { probe } from "../engine/probe.js"
17
+ import { runTool } from "../engine/tool.js"
18
+ import { editHome } from "./paths.js"
19
+
20
+ const VIDEO = new Set([".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi"])
21
+ const REPORT_MS = 10_000 // At most this often (TOOLS_AND_CONTRACTS §5)
22
+ const BEAT_MS = 60_000 // A long render with nothing new still says it's alive
23
+ const RETRY_MS = 30_000
24
+ const OUTBOX_DAYS = 7
25
+ export const PREVIEW_MAX_BYTES = 47_185_920 // 45 MiB (EH-23)
26
+ const PREVIEW_TARGET_BYTES = 40 * 1024 * 1024
27
+ const AUDIO_KBPS = 96
28
+ const FLICKS = 705_600_000
29
+ const FILE_QUESTION_S = 600
30
+ const TAKE_QUESTION_S = 300
31
+ const TASTE_QUESTION_S = 3600
32
+ const TAKE_MARGIN = 0.1
33
+ const CLIP_SECONDS = 5
34
+ const WAIT_S = 25
35
+
36
+ // The Host's reasons, in Kriya's words (TOOLS_AND_CONTRACTS §9)
37
+ const CODES = { low_disk: "disk_low", no_take: "no_media", missing_feature: "runtime_missing", signed_out: "model_unavailable" }
38
+ const codeOf = (error) => {
39
+ const reason = CODES[error?.reason] ?? error?.reason
40
+ return typeof reason === "string" && /^[a-z_]{1,32}$/.test(reason) ? reason : "failed"
41
+ }
42
+
43
+ /** A number that changes with every report: how the worker hears the computer is alive. */
44
+ const beat = () => Math.floor(Date.now() / 1000) % 2_000_000_000
45
+
46
+ /** The videos the brief could mean: most words of the brief in the name, then the newest. */
47
+ export function rankFiles(folder, brief) {
48
+ const words = brief.toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) ?? []
49
+ return readdirSync(folder, { withFileTypes: true })
50
+ .filter((entry) => entry.isFile() && !entry.name.startsWith(".") && VIDEO.has(extname(entry.name).toLowerCase()))
51
+ .map((entry) => {
52
+ const path = join(folder, entry.name)
53
+ const name = entry.name.toLowerCase()
54
+ return { path, name: entry.name, hits: words.filter((word) => name.includes(word)).length, at: statSync(path).mtimeMs }
55
+ })
56
+ .sort((a, b) => b.hits - a.hits || b.at - a.at)
57
+ }
58
+
59
+ export const chooseFile = (folder, brief) => rankFiles(folder, brief)[0]?.path ?? null
60
+
61
+ /** Two takes the index can't tell apart: a real choice, at most two per job (TAVI §5). */
62
+ export function closeTakes(index, asset, margin = TAKE_MARGIN) {
63
+ const sentences = new Map(index.sentences.filter((s) => s.asset === asset).map((s) => [s.id, s]))
64
+ const groups = new Map()
65
+ for (const take of index.takes ?? []) {
66
+ if (sentences.has(take.sentence) && take.rank <= 2) groups.set(take.group, [...(groups.get(take.group) ?? []), take])
67
+ }
68
+ const close = []
69
+ for (const [group, takes] of groups) {
70
+ if (takes.length !== 2) continue
71
+ const [first, second] = takes.sort((x, y) => x.rank - y.rank).map((t) => sentences.get(t.sentence))
72
+ if (first.score > 0 && second.score > 0 && Math.abs(first.score - second.score) <= margin * Math.max(first.score, second.score)) close.push({ group, first, second })
73
+ }
74
+ return close.slice(0, 2)
75
+ }
76
+
77
+ /** The length in the brief's own words: "45 s", "90 seconds", "2 minutes". */
78
+ export function secondsIn(brief) {
79
+ const found = /\b(\d{1,3})\s*-?\s*(s|sec|secs|second|seconds|min|mins|minute|minutes)\b/i.exec(brief)
80
+ if (!found) return undefined
81
+ const seconds = Number(found[1]) * (/^m/i.test(found[2]) ? 60 : 1)
82
+ return seconds >= 5 && seconds <= 600 ? seconds : undefined
83
+ }
84
+
85
+ /**
86
+ * A file small enough to upload: the master when it fits, else a lower bitrate that
87
+ * does. @returns {Promise<string | null>} null when even that won't fit
88
+ */
89
+ export async function previewOf(file, { durationSeconds, capabilities, work, run = runTool, signal, maxBytes = PREVIEW_MAX_BYTES }) {
90
+ if (statSync(file).size <= maxBytes) return file
91
+ const kbps = Math.floor((PREVIEW_TARGET_BYTES * 8) / 1000 / Math.max(1, durationSeconds)) - AUDIO_KBPS
92
+ if (!(kbps >= 100)) return null
93
+ mkdirSync(work, { recursive: true })
94
+ const output = join(work, `preview-${basename(file)}`)
95
+ await run("ffmpeg", previewArgs({ source: file, output, encoder: encoderFor(capabilities, "proxy"), videoKbps: kbps, audioKbps: AUDIO_KBPS }), { signal })
96
+ return statSync(output).size <= maxBytes ? output : null
97
+ }
98
+
99
+ function sha256Of(file) {
100
+ return new Promise((done, fail) => {
101
+ const hash = createHash("sha256")
102
+ createReadStream(file)
103
+ .on("data", (chunk) => hash.update(chunk))
104
+ .on("error", fail)
105
+ .on("end", () => done(hash.digest("hex")))
106
+ })
107
+ }
108
+
109
+ /** @param {{ home: string, projects: object, jobs: () => object, tools: () => Promise<any>, log: (line: string) => void, device?: () => any, send?: Function, put?: typeof fetch, probeFile?: typeof probe, reportMs?: number, beatMs?: number, retryMs?: number }} options */
110
+ export function createTavi({ home, projects, taste = projects.taste, jobs, tools, log, device = readDevice, send, put = fetch, probeFile = probe, runClip = runTool, reportMs = REPORT_MS, beatMs = BEAT_MS, retryMs = RETRY_MS }) {
111
+ const request =
112
+ send ??
113
+ ((path, body, { method = "POST", signal } = {}) => {
114
+ const signedIn = device()
115
+ if (!signedIn) throw new KriyaError(401, "signed_out", "This computer isn't signed in to Kriya.")
116
+ return call(signedIn.url, method, path, { token: signedIn.token, ...(body && { body }), ...(signal && { signal }) })
117
+ })
118
+ const post = (path, body) => request(path, body)
119
+
120
+ const tracked = new Map() // dispatch id → { hostJob, canceling, sentAt, percent, defaulted, abort }
121
+ const outboxFile = join(editHome(home), "tavi-outbox.json")
122
+
123
+ // A final report survives a closed lid and a restart: it's written before it's sent
124
+ const readOutbox = () => {
125
+ try {
126
+ return JSON.parse(readFileSync(outboxFile, "utf8"))
127
+ } catch {
128
+ return {}
129
+ }
130
+ }
131
+ const writeOutbox = (box) => {
132
+ mkdirSync(dirname(outboxFile), { recursive: true })
133
+ const temporary = `${outboxFile}.tmp`
134
+ writeFileSync(temporary, JSON.stringify(box), { mode: 0o600 })
135
+ renameSync(temporary, outboxFile)
136
+ }
137
+ let flushing = null
138
+ const flush = () =>
139
+ (flushing ??= (async () => {
140
+ const box = readOutbox()
141
+ for (const [id, entry] of Object.entries(box)) {
142
+ try {
143
+ await post(`/dispatch/${id}`, { status: entry.status, result: entry.result })
144
+ delete box[id]
145
+ } catch (error) {
146
+ // Refused for good (finished, revoked), or kept so long nobody is waiting
147
+ if (error instanceof KriyaError && [400, 404].includes(error.status)) delete box[id]
148
+ else if (Date.now() - entry.at > OUTBOX_DAYS * 86_400_000) delete box[id]
149
+ else log(`couldn't report a job: ${error.code ?? error.name}`)
150
+ }
151
+ }
152
+ writeOutbox(box)
153
+ })().finally(() => (flushing = null)))
154
+ const final = async (id, status, result) => {
155
+ tracked.delete(id)
156
+ writeOutbox({ ...readOutbox(), [id]: { status, result, at: Date.now() } })
157
+ await flush()
158
+ }
159
+
160
+ const progress = (id, entry, percent) => {
161
+ entry.percent = percent ?? entry.percent
162
+ entry.sentAt = Date.now()
163
+ post(`/dispatch/${id}`, { status: "running", result: { stage: entry.waiting ? "waiting_for_you" : "editing", percent: entry.percent ?? 0, beat: beat() } }).catch((error) => log(`couldn't report progress: ${error.code ?? error.name}`))
164
+ }
165
+
166
+ async function upload(jobId, file, durationFlicks, kind = "preview") {
167
+ const { size: bytes } = statSync(file)
168
+ const sha256 = await sha256Of(file)
169
+ const { id, uploadUrl } = await post(`/editing/jobs/${jobId}/previews`, { kind, bytes, sha256, ...(Number.isSafeInteger(durationFlicks) && { durationFlicks }) })
170
+ const url = new URL(uploadUrl)
171
+ if (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost") throw new Error("not a safe upload link")
172
+ const res = await put(uploadUrl, { method: "PUT", body: Readable.toWeb(createReadStream(file)), duplex: "half", headers: { "content-type": "video/mp4", "content-length": String(bytes) } })
173
+ if (!res.ok) throw new Error(`upload answered ${res.status}`)
174
+ await post(`/editing/jobs/${jobId}/previews/${id}`)
175
+ return id
176
+ }
177
+
178
+ /**
179
+ * A decision card, and its answer. Each has a default and a timeout, so a person who
180
+ * never answers still gets an edit, with the default counted for the report. With the
181
+ * cards off on this Kriya, or no way to reach it, the default stands at once.
182
+ */
183
+ // Waits for a card's answer; undefined when it closed without one
184
+ async function answerOf(questionId, deadline, signal) {
185
+ while (Date.now() < deadline) {
186
+ signal?.throwIfAborted()
187
+ try {
188
+ const limit = AbortSignal.timeout((WAIT_S + 15) * 1000)
189
+ const answer = await request(`/editing/questions/${questionId}?wait=${WAIT_S}`, undefined, { method: "GET", signal: signal ? AbortSignal.any([signal, limit]) : limit })
190
+ if (answer.status === "answered" && Number.isInteger(answer.option)) return answer.option
191
+ if (answer.status !== "open") return undefined
192
+ } catch (error) {
193
+ if (signal?.aborted) throw error
194
+ if (error instanceof KriyaError && [400, 404].includes(error.status)) return undefined
195
+ await new Promise((done) => setTimeout(done, Math.min(retryMs, 5_000)))
196
+ }
197
+ }
198
+ return undefined
199
+ }
200
+
201
+ // "Remember this?" (TAVI §5): asked once, while the job is open, and never waited on. Only
202
+ // the person's yes on the card confirms; silence leaves it for the Studio's Taste screen
203
+ let offers = 0
204
+ async function offerTaste(jobId) {
205
+ const proposal = taste?.nextToAsk()
206
+ if (!proposal) return
207
+ let asked
208
+ try {
209
+ asked = await post(`/editing/jobs/${jobId}/questions`, { kind: "taste", prompt: proposal.sentence, options: [{ label: "Yes, use it" }, { label: "Not now" }], defaultOption: 1, timeoutSeconds: TASTE_QUESTION_S })
210
+ } catch (error) {
211
+ log(`no taste card: ${error.code ?? error.name}`)
212
+ return
213
+ }
214
+ offers++
215
+ void answerOf(asked.id, Date.now() + (TASTE_QUESTION_S + 30) * 1000)
216
+ .then((option) => option === 0 && taste.confirm(proposal.key))
217
+ .catch(() => {})
218
+ .finally(() => offers--)
219
+ }
220
+
221
+ async function askPerson(id, entry, jobId, card) {
222
+ const fallback = card.defaultOption
223
+ let asked
224
+ try {
225
+ asked = await post(`/editing/jobs/${jobId}/questions`, card)
226
+ } catch (error) {
227
+ log(`no card: ${error.code ?? error.name}`)
228
+ return fallback
229
+ }
230
+ entry.waiting = true
231
+ progress(id, entry)
232
+ try {
233
+ const option = await answerOf(asked.id, Date.now() + card.timeoutSeconds * 1000 + 30_000, entry.abort?.signal)
234
+ if (option !== undefined && option < card.options.length) return option
235
+ } finally {
236
+ entry.waiting = false
237
+ }
238
+ entry.defaulted = (entry.defaulted ?? 0) + 1
239
+ return fallback
240
+ }
241
+
242
+ async function clipOf(jobId, source, sentence, capabilities) {
243
+ const work = join(editHome(home), "tavi-previews")
244
+ mkdirSync(work, { recursive: true })
245
+ const output = join(work, `clip-${jobId}-${sentence.id.replace(/[^\w-]/g, "_")}.mp4`)
246
+ const fromSeconds = sentence.start / FLICKS
247
+ const seconds = Math.min(CLIP_SECONDS, Math.max(1, (sentence.end - sentence.start) / FLICKS))
248
+ await runClip("ffmpeg", clipArgs({ source, output, encoder: encoderFor(capabilities, "proxy"), fromSeconds, seconds }))
249
+ return upload(jobId, output, Math.round(seconds * FLICKS), "clip")
250
+ }
251
+
252
+ // A verdict without a preview is still a verdict: the card says where the file is
253
+ async function sendPreview(request, result) {
254
+ try {
255
+ const { capabilities } = await tools()
256
+ const { facts } = await probeFile(result.file)
257
+ const file = await previewOf(result.file, { durationSeconds: facts.duration / FLICKS, capabilities, work: join(editHome(home), "tavi-previews") })
258
+ if (file) await upload(request.dispatchJob, file, facts.duration)
259
+ } catch (error) {
260
+ log(`no preview: ${error.code ?? error.name}`)
261
+ }
262
+ }
263
+
264
+ // What the person sent for this revision, and an agent's approved change
265
+ async function notesFor(jobId, change) {
266
+ const sent = await request(`/editing/jobs/${jobId}/notes`, undefined, { method: "GET" }).catch((error) => {
267
+ log(`no notes: ${error.code ?? error.name}`)
268
+ return { notes: [] }
269
+ })
270
+ return [...(sent.notes ?? []).map((n) => ({ at: n.atFlicks, text: n.body })), ...(change ? [{ text: change }] : [])]
271
+ }
272
+
273
+ const heartbeat = setInterval(() => {
274
+ for (const [id, entry] of tracked) if (Date.now() - entry.sentAt >= beatMs) progress(id, entry)
275
+ }, Math.max(50, Math.min(beatMs, reportMs)))
276
+ heartbeat.unref?.()
277
+ const retry = setInterval(() => {
278
+ if (Object.keys(readOutbox()).length) flush().catch(() => {})
279
+ }, retryMs)
280
+ retry.unref?.()
281
+
282
+ return {
283
+ post,
284
+
285
+ /** The daemon's handover. Answers at once; a question about the file waits in the background. */
286
+ async accept({ dispatch, folder, job, brief, recipe, effort, revisionOf, change }) {
287
+ if (tracked.has(dispatch)) return { accepted: true }
288
+ const entry = { hostJob: null, canceling: false, sentAt: 0, abort: new AbortController() }
289
+ const refuse = (code) => final(dispatch, "failed", { code }).then(() => ({ accepted: false, code }))
290
+ tracked.set(dispatch, entry)
291
+ const begin = async (file) => {
292
+ const known = projects.list().find((p) => dirname(p.file) === folder)
293
+ const state = known ? await projects.get(known.id) : await projects.create({ name: basename(folder), folder, offered: true })
294
+ // A revision of a cut this project holds; anything else is a new cut
295
+ const notes = revisionOf ? await notesFor(job, change) : []
296
+ if (revisionOf && notes.length && state.log.current.deliverables.length) {
297
+ const started = jobs().start(state, { kind: "revise", notes, dispatch, dispatchJob: job })
298
+ entry.hostJob = started.id
299
+ return { accepted: true }
300
+ }
301
+ const asset = state.log.current.assets.find((a) => a.kind === "video" && (a.path === file || join(state.folder, a.path) === file)) ?? (await projects.addAsset(state, file))
302
+ const seconds = secondsIn(brief)
303
+ const started = jobs().start(state, { kind: "make", asset: asset.id, brief: { effort, ...(seconds && { targetDuration: seconds * FLICKS }) }, dispatch, dispatchJob: job })
304
+ entry.hostJob = started.id
305
+ return { accepted: true }
306
+ }
307
+ const failed = (error) => {
308
+ log(`a job from Kriya didn't start: ${error.reason ?? error.name}`)
309
+ return refuse(codeOf(error))
310
+ }
311
+ // Only this recipe reaches a make job so far (ED11, ED12)
312
+ if (recipe && recipe !== "reel-talking-head") return refuse("not_allowed")
313
+ try {
314
+ const files = rankFiles(folder, brief)
315
+ if (!files.length && !revisionOf) return await refuse("no_media")
316
+ // Two that fit the brief equally: it asks rather than guesses (TAVI §3). A revision has its file
317
+ if (!revisionOf && files.length > 1 && files[0].hits === files[1].hits) {
318
+ const options = files.slice(0, 4)
319
+ void askPerson(dispatch, entry, job, {
320
+ kind: "file",
321
+ prompt: "Which recording did you mean?",
322
+ options: options.map((f) => ({ label: f.name.slice(0, 200) })),
323
+ defaultOption: 0,
324
+ timeoutSeconds: FILE_QUESTION_S,
325
+ })
326
+ .then((option) => begin(options[option].path))
327
+ .catch((error) => (entry.abort.signal.aborted ? final(dispatch, "canceled", { code: "canceled" }) : failed(error)))
328
+ return { accepted: true }
329
+ }
330
+ return await begin(files[0]?.path)
331
+ } catch (error) {
332
+ return failed(error)
333
+ }
334
+ },
335
+
336
+ /** The make job's question about its takes, once the footage is indexed. @returns picks by group */
337
+ async chooseTakes(request, state, asset, { sourcePath }) {
338
+ const entry = tracked.get(request.dispatch)
339
+ if (!entry) return null
340
+ entry.abort ??= new AbortController()
341
+ const close = closeTakes(state.index, asset)
342
+ if (!close.length) return null
343
+ const picks = {}
344
+ const { capabilities } = await tools()
345
+ for (const { group, first, second } of close) {
346
+ let clips
347
+ try {
348
+ // No clips, no card: a choice between two words on a screen isn't worth asking
349
+ clips = [await clipOf(request.dispatchJob, sourcePath(asset), first, capabilities), await clipOf(request.dispatchJob, sourcePath(asset), second, capabilities)]
350
+ } catch (error) {
351
+ log(`no clips for a card: ${error.code ?? error.name}`)
352
+ continue
353
+ }
354
+ const option = await askPerson(request.dispatch, entry, request.dispatchJob, {
355
+ kind: "take",
356
+ prompt: "Which take?",
357
+ options: [
358
+ { label: "Take 1", clip: clips[0] },
359
+ { label: "Take 2", clip: clips[1] },
360
+ ],
361
+ defaultOption: 0,
362
+ timeoutSeconds: TAKE_QUESTION_S,
363
+ })
364
+ picks[group] = (option === 1 ? second : first).id
365
+ }
366
+ return picks
367
+ },
368
+
369
+ /** Kriya said canceling. false when this Host doesn't know the job: the daemon closes it (EH-04). */
370
+ cancel({ dispatch }) {
371
+ if (Object.hasOwn(readOutbox(), dispatch)) return true // Already over; its report is on the way
372
+ const entry = tracked.get(dispatch)
373
+ if (!entry) return false
374
+ entry.canceling = true
375
+ // Still waiting on a question: nothing is running yet
376
+ if (!entry.hostJob) {
377
+ entry.abort?.abort(new Error("Canceled"))
378
+ return true
379
+ }
380
+ return jobs().cancel(entry.hostJob) || (tracked.delete(dispatch), false)
381
+ },
382
+
383
+ /** Every update of a job with a dispatch id, including one resumed after a crash. */
384
+ async onUpdate(request, view, error) {
385
+ const id = request.dispatch
386
+ const entry = tracked.get(id) ?? { hostJob: view.id, canceling: false, sentAt: 0, abort: new AbortController() }
387
+ tracked.set(id, entry)
388
+ if (view.status === "running") {
389
+ if (Date.now() - entry.sentAt >= reportMs) progress(id, entry, view.progress)
390
+ else entry.percent = view.progress
391
+ return
392
+ }
393
+ if (view.status === "canceled") {
394
+ // Only after Kriya said canceling: from running it would be refused (EH-17)
395
+ return final(id, entry.canceling ? "canceled" : "failed", entry.canceling ? { code: "canceled" } : { code: "stopped_on_computer" })
396
+ }
397
+ if (view.status === "failed") return final(id, "failed", { code: codeOf(error) })
398
+ if (view.status !== "done") return
399
+ const result = JSON.parse(view.output ?? "{}")
400
+ if (!result.file || !["delivered", "delivered_with_notes", "blocked"].includes(result.verdict)) return final(id, "failed", { code: "not_checked" })
401
+ await sendPreview(request, result)
402
+ await offerTaste(request.dispatchJob)
403
+ const gates = (result.gates ?? []).slice(0, 60).flatMap((g) => (/^[A-Za-z0-9_-]{1,32}$/.test(g.id ?? "") ? [{ gate: g.id, level: g.status === "passed" ? "pass" : g.status === "not_checked" ? "unchecked" : g.severity === "note" ? "note" : g.status === "failed" ? "fail" : "skipped" }] : []))
404
+ const count = (n) => (Number.isInteger(n) && n > 0 ? Math.min(n, 100) : undefined)
405
+ const facts = { applied: count(result.applied), skipped: count(result.skipped), defaulted: count(entry.defaulted) }
406
+ return final(id, "done", { outcome: result.verdict, gates, notes: Math.min(result.notes?.length ?? 0, 1000), ...Object.fromEntries(Object.entries(facts).filter(([, n]) => n)) })
407
+ },
408
+
409
+ /** Anything still to say: the Host doesn't go idle before it's said. */
410
+ pending: () => tracked.size + offers + Object.keys(readOutbox()).length,
411
+ flush,
412
+ close() {
413
+ clearInterval(heartbeat)
414
+ clearInterval(retry)
415
+ },
416
+ }
417
+ }
@@ -0,0 +1,141 @@
1
+ // Watch folders (TAVI_INTEGRATION §8, EDD-47). Off unless the person adds a folder on this
2
+ // computer. When a new recording settles, Kriya hears its name and duration, nothing else,
3
+ // and nothing runs until the person taps its card (ES-21).
4
+
5
+ import { createHash } from "node:crypto"
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs"
7
+ import { homedir } from "node:os"
8
+ import { basename, dirname, extname, join, sep } from "node:path"
9
+
10
+ import { KriyaError } from "../../api.js"
11
+ import { probe } from "../engine/probe.js"
12
+ import { editHome } from "./paths.js"
13
+
14
+ const VIDEO = new Set([".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi"])
15
+ const FLICKS = 705_600_000
16
+ const TICK_MS = 60_000
17
+ const SEEN_MAX = 2000
18
+
19
+ const fileOf = (home) => join(editHome(home), "watch.json")
20
+
21
+ /** @returns {{ folders: string[], seen: Record<string, { size: number, mtime: number, told?: boolean }> }} */
22
+ function readState(home) {
23
+ try {
24
+ const kept = JSON.parse(readFileSync(fileOf(home), "utf8"))
25
+ return { folders: Array.isArray(kept.folders) ? kept.folders : [], seen: kept.seen && typeof kept.seen === "object" ? kept.seen : {} }
26
+ } catch {
27
+ return { folders: [], seen: {} }
28
+ }
29
+ }
30
+
31
+ function writeState(home, state) {
32
+ const file = fileOf(home)
33
+ mkdirSync(dirname(file), { recursive: true })
34
+ const temporary = `${file}.tmp`
35
+ writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 })
36
+ renameSync(temporary, file)
37
+ }
38
+
39
+ /** The folder's id, as the daemon offers it (src/daemon.js projectId). */
40
+ export const folderId = (path) => createHash("sha256").update(path).digest("hex").slice(0, 16)
41
+
42
+ const videosIn = (folder) => {
43
+ try {
44
+ return readdirSync(folder, { withFileTypes: true })
45
+ .filter((entry) => entry.isFile() && !entry.name.startsWith(".") && VIDEO.has(extname(entry.name).toLowerCase()))
46
+ .map((entry) => join(folder, entry.name))
47
+ } catch {
48
+ return [] // A folder that's gone, or a drive that's out: nothing to say today
49
+ }
50
+ }
51
+
52
+ const statOf = (file) => {
53
+ const { size, mtimeMs } = statSync(file)
54
+ return { size, mtime: mtimeMs }
55
+ }
56
+
57
+ /** What's in it now counts as old, so adding a folder sends nothing. */
58
+ export function watchFolder(raw, { home, personal = homedir() }) {
59
+ const path = realpathSync(raw)
60
+ if (!statSync(path).isDirectory()) throw new Error("That isn't a folder.")
61
+ if (path === realpathSync(personal) || path === sep || /^[A-Za-z]:\\?$/.test(path)) throw new Error("Watch one folder of recordings, not your whole home folder or a drive.")
62
+ const state = readState(home)
63
+ if (!state.folders.includes(path)) state.folders.push(path)
64
+ for (const file of videosIn(path)) state.seen[file] = { ...statOf(file), told: true }
65
+ writeState(home, state)
66
+ return path
67
+ }
68
+
69
+ export function unwatchFolder(raw, { home }) {
70
+ const state = readState(home)
71
+ const path = existsSync(raw) ? realpathSync(raw) : raw
72
+ const had = state.folders.includes(path)
73
+ state.folders = state.folders.filter((folder) => folder !== path)
74
+ for (const file of Object.keys(state.seen)) if (dirname(file) === path) delete state.seen[file]
75
+ writeState(home, state)
76
+ return had
77
+ }
78
+
79
+ export const watchedFolders = ({ home }) => readState(home).folders
80
+
81
+ /**
82
+ * @param {{ home: string, send: (path: string, body: object) => Promise<any>, log: (line: string) => void, probeFile?: typeof probe, tickMs?: number }} options
83
+ */
84
+ export function createWatcher({ home, send, log, probeFile = probe, tickMs = TICK_MS }) {
85
+ let busy = false
86
+
87
+ /** One look: a file reported once it has stayed the same size between two looks. */
88
+ async function tick() {
89
+ if (busy) return
90
+ busy = true
91
+ try {
92
+ const state = readState(home)
93
+ let changed = false
94
+ for (const folder of state.folders) {
95
+ for (const file of videosIn(folder)) {
96
+ let now
97
+ try {
98
+ now = statOf(file)
99
+ } catch {
100
+ continue
101
+ }
102
+ const known = state.seen[file]
103
+ if (known?.told) continue
104
+ if (!known || known.size !== now.size || known.mtime !== now.mtime || now.size === 0) {
105
+ state.seen[file] = now
106
+ changed = true
107
+ continue
108
+ }
109
+ try {
110
+ const { facts } = await probeFile(file)
111
+ if (!facts.duration) throw new Error("no duration")
112
+ await send("/editing/found", { project: folderId(folder), name: basename(file).slice(0, 200), seconds: Math.round(facts.duration / FLICKS) })
113
+ state.seen[file] = { ...now, told: true }
114
+ changed = true
115
+ } catch (error) {
116
+ // Off on this Kriya, or still being written: the next look tries again. A folder
117
+ // this computer doesn't offer, or a full Inbox, stays quiet until that changes
118
+ if (!(error instanceof KriyaError && [404, 409, 429].includes(error.status))) log(`watch: ${error.code ?? error.name}`)
119
+ }
120
+ }
121
+ }
122
+ const files = Object.keys(state.seen)
123
+ if (files.length > SEEN_MAX) {
124
+ for (const file of files.slice(0, files.length - SEEN_MAX)) delete state.seen[file]
125
+ changed = true
126
+ }
127
+ if (changed) writeState(home, state)
128
+ } finally {
129
+ busy = false
130
+ }
131
+ }
132
+
133
+ const timer = setInterval(() => tick().catch((error) => log(`watch: ${error.name}`)), tickMs)
134
+ timer.unref?.()
135
+ return {
136
+ tick,
137
+ /** Folders on the list: the Host stays up for them. */
138
+ count: () => readState(home).folders.length,
139
+ close: () => clearInterval(timer),
140
+ }
141
+ }
@@ -0,0 +1,109 @@
1
+ // index.sqlite (DATA_MODEL §3.1): what the layers found, one file per project in
2
+ // ~/.kriya/edit/<project id>/. Rows are keyed by the media's fingerprint, so two
3
+ // assets of the same file share one set of results; ids are made per asset on read
4
+ // ("a1:w0"). Times are integer flicks. Everything but `corrections` can be rebuilt.
5
+
6
+ import { DatabaseSync } from "node:sqlite"
7
+
8
+ const SCHEMA = `
9
+ create table if not exists assets (asset text primary key, media text not null, kind text not null);
10
+ create table if not exists layers (media text not null, layer text not null, model_version text not null, status text not null, notice text, data text, updated_at text not null, primary key (media, layer));
11
+ create table if not exists words (media text not null, n integer not null, start integer not null, "end" integer not null, text text not null, lang text, speaker text, conf real, flags text not null default '', primary key (media, n));
12
+ create virtual table if not exists words_fts using fts5 (text, media unindexed, n unindexed);
13
+ create table if not exists corrections (asset text not null, word text not null, text text not null, at text not null);
14
+ create table if not exists sentences (media text not null, n integer not null, start integer not null, "end" integer not null, first_word integer not null, last_word integer not null, speaker text, take_group integer, score real, primary key (media, n));
15
+ create table if not exists takes (media text not null, "group" integer not null, sentence integer not null, rank integer not null, signals text not null, primary key (media, "group", sentence));
16
+ create table if not exists shots (media text not null, n integer not null, start integer not null, "end" integer not null, kind text not null, blur real, exposure real, shake real, motion real, primary key (media, n));
17
+ create table if not exists faces (media text not null, shot integer, t integer not null, box text not null, eye text, chin text, identity integer, gaze text);
18
+ create table if not exists events (media text not null, start integer not null, "end" integer not null, kind text not null, conf real);
19
+ create table if not exists beats (media text not null, n integer not null, t integer not null, downbeat integer not null, strength real, primary key (media, n));
20
+ create table if not exists bars (media text not null, n integer not null, start integer not null, "end" integer not null, energy real, primary key (media, n));
21
+ create index if not exists faces_media on faces (media, t);
22
+ create index if not exists events_media on events (media, kind, start);
23
+ `
24
+
25
+ // The tables each layer owns: a re-run replaces exactly these rows
26
+ const OWNED = { L1: ["events"], L2: ["words", "words_fts"], L5: ["sentences", "takes"], L6: ["shots"], L8: ["faces"], L12: ["beats", "bars"] }
27
+
28
+ const flagList = (text) => (text ? text.split(",") : [])
29
+
30
+ export function openIndexDb(file) {
31
+ const db = new DatabaseSync(file)
32
+ if (file !== ":memory:") db.exec("pragma journal_mode = wal")
33
+ db.exec(SCHEMA)
34
+
35
+ const tx = (work) => {
36
+ db.exec("begin")
37
+ try {
38
+ const value = work()
39
+ db.exec("commit")
40
+ return value
41
+ } catch (error) {
42
+ db.exec("rollback")
43
+ throw error
44
+ }
45
+ }
46
+
47
+ const mediaOf = (asset) => db.prepare("select media from assets where asset = ?").get(asset)?.media ?? null
48
+
49
+ return {
50
+ db,
51
+ tx,
52
+ close: () => db.close(),
53
+
54
+ setAsset: (asset, media, kind) => db.prepare("insert or replace into assets (asset, media, kind) values (?, ?, ?)").run(asset, media, kind),
55
+ mediaOf,
56
+
57
+ layer(media, layer) {
58
+ const row = db.prepare("select * from layers where media = ? and layer = ?").get(media, layer)
59
+ return row ? { ...row, data: row.data ? JSON.parse(row.data) : null } : null
60
+ },
61
+ layers: (media) => db.prepare("select layer, model_version, status, notice from layers where media = ? order by layer").all(media).map((row) => ({ ...row })),
62
+
63
+ /** Replaces a layer's rows and status in one transaction, so a crash leaves the old result or the new one. */
64
+ saveLayer(media, layer, { version, status, notice = null, data = null, write }) {
65
+ tx(() => {
66
+ for (const table of OWNED[layer] ?? []) db.prepare(`delete from ${table} where media = ?`).run(media)
67
+ write?.(db)
68
+ db.prepare("insert or replace into layers (media, layer, model_version, status, notice, data, updated_at) values (?, ?, ?, ?, ?, ?, ?)").run(media, layer, version, status, notice, data === null ? null : JSON.stringify(data), new Date().toISOString())
69
+ })
70
+ },
71
+
72
+ /** Rows for Edit Core and the views, for these assets (DATA_MODEL §3.1 shapes, ids per asset). */
73
+ read(assets = db.prepare("select asset from assets order by asset").all().map((row) => row.asset)) {
74
+ const raw = { words: [], sentences: [], takes: [], shots: [], faces: [], silences: [], beats: [], bars: [], timestamps: {}, subjects: {} }
75
+ for (const asset of assets) {
76
+ const media = mediaOf(asset)
77
+ if (!media) continue
78
+ for (const w of db.prepare('select * from words where media = ? order by n').all(media)) {
79
+ raw.words.push({ id: `${asset}:w${w.n}`, asset, start: w.start, end: w.end, text: w.text, conf: w.conf, flags: flagList(w.flags) })
80
+ }
81
+ for (const s of db.prepare('select * from sentences where media = ? order by n').all(media)) {
82
+ raw.sentences.push({ id: `${asset}:s${s.n}`, asset, start: s.start, end: s.end, firstWord: `${asset}:w${s.first_word}`, lastWord: `${asset}:w${s.last_word}`, takeGroup: s.take_group === null ? null : `${asset}:g${s.take_group}`, score: s.score })
83
+ }
84
+ for (const t of db.prepare('select * from takes where media = ? order by "group", rank').all(media)) {
85
+ raw.takes.push({ group: `${asset}:g${t.group}`, sentence: `${asset}:s${t.sentence}`, rank: t.rank, signals: JSON.parse(t.signals) })
86
+ }
87
+ for (const s of db.prepare("select * from shots where media = ? order by n").all(media)) {
88
+ raw.shots.push({ id: `${asset}:sh${s.n}`, asset, start: s.start, end: s.end, kind: s.kind, blur: s.blur, exposure: s.exposure, shake: s.shake, motion: s.motion })
89
+ }
90
+ for (const f of db.prepare("select * from faces where media = ? order by t").all(media)) {
91
+ raw.faces.push({ asset, shot: f.shot === null ? null : `${asset}:sh${f.shot}`, t: f.t, box: JSON.parse(f.box), identity: f.identity })
92
+ }
93
+ // The reframe solver's subject: the face track seen most, its centre and box width per sample (ED7, ED11)
94
+ const own = raw.faces.filter((f) => f.asset === asset && f.shot !== null)
95
+ const counts = new Map()
96
+ for (const f of own) counts.set(f.identity, (counts.get(f.identity) ?? 0) + 1)
97
+ const main = [...counts].sort((a, b) => b[1] - a[1])[0]?.[0]
98
+ if (main !== undefined) raw.subjects[asset] = own.filter((f) => f.identity === main).map((f) => ({ t: f.t, x: f.box.x + f.box.w / 2, w: f.box.w, shot: f.shot }))
99
+ for (const e of db.prepare("select start, \"end\" from events where media = ? and kind = 'silence' order by start").all(media)) raw.silences.push({ asset, start: e.start, end: e.end })
100
+ for (const b of db.prepare("select * from beats where media = ? order by n").all(media)) raw.beats.push({ id: `${asset}:b${b.n}`, asset, t: b.t, downbeat: b.downbeat === 1, strength: b.strength })
101
+ for (const b of db.prepare('select * from bars where media = ? order by n').all(media)) raw.bars.push({ asset, start: b.start, end: b.end, energy: b.energy })
102
+ const probe = db.prepare("select data from layers where media = ? and layer = 'L0' and status = 'ok'").get(media)
103
+ const timestamps = probe?.data ? JSON.parse(probe.data).timestamps : null
104
+ if (timestamps) raw.timestamps[asset] = timestamps
105
+ }
106
+ return raw
107
+ },
108
+ }
109
+ }