@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,391 @@
1
+ // The Studio's own origin (STUDIO_APP_AND_BROWSER §3): HTTP on 127.0.0.1, fenced on
2
+ // every request, and an owner-only socket with the same routes. Typed requests only:
3
+ // no route runs a command, and every path passes guardPath.
4
+
5
+ import { createHash, createHmac, randomBytes } from "node:crypto"
6
+ import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs"
7
+ import { basename, extname, isAbsolute, join } from "node:path"
8
+ import { pipeline } from "node:stream/promises"
9
+
10
+ import { compile } from "../core/plan.js"
11
+ import { solve } from "../core/solver.js"
12
+ import { LOOKS } from "../engine/captions.js"
13
+ import { ENGINE_VERSION, guardPath } from "../engine/index.js"
14
+ import { EngineFailure } from "../engine/tool.js"
15
+ import { activeRuntime } from "../runtime/setup.js"
16
+
17
+ const HEADERS = {
18
+ "cross-origin-opener-policy": "same-origin",
19
+ "cross-origin-embedder-policy": "require-corp",
20
+ "content-security-policy": "default-src 'self'; connect-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; worker-src 'self' blob:; frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
21
+ "x-content-type-options": "nosniff",
22
+ "cache-control": "no-store",
23
+ }
24
+ const COOKIE = "kriya_edit"
25
+ const MAX_BODY = 4 * 1024 * 1024
26
+ // The Studio app, built by `npm run build:studio` (ED6)
27
+ const STUDIO = join(import.meta.dirname, "..", "..", "..", "studio", "dist")
28
+ const STUDIO_FILES = { "/": ["index.html", "text/html; charset=utf-8"], "/studio.js": ["studio.js", "text/javascript"], "/studio.css": ["studio.css", "text/css"] }
29
+ const TYPES = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".m4a": "audio/mp4", ".wav": "audio/wav", ".mp3": "audio/mpeg", ".jpg": "image/jpeg", ".json": "application/json" }
30
+
31
+ // An inline icon, so the browser doesn't ask for /favicon.ico (a 404 in the console)
32
+ const LAUNCH_PAGE = `<!doctype html><title>Kriya Editing Studio</title><link rel="icon" href="data:,"><p>Opening…</p><script src="/launch.js"></script>`
33
+ // The token is in the fragment, so it never reaches a log or a Referer
34
+ const LAUNCH_SCRIPT = `const token = location.hash.slice(1);
35
+ history.replaceState(null, "", "/launch");
36
+ fetch("/session", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ token }) }).then(async (r) => {
37
+ document.querySelector("p").textContent = r.ok ? "Signed in." : "This link has been used. Run kriya edit again.";
38
+ if (!r.ok) return;
39
+ const { back } = await r.json();
40
+ try { back ? sessionStorage.setItem("kriya-edit-back", back) : sessionStorage.removeItem("kriya-edit-back"); } catch {}
41
+ location.replace("/");
42
+ });`
43
+ const HOME_PAGE = `<!doctype html><title>Kriya Editing Studio</title><p>The Edit Host is running, but the Studio isn't built. Run npm run build:studio.</p>`
44
+
45
+ /** Where "Back to Kriya Harness" may go: the harness's own loopback page, nothing else. */
46
+ const backOf = (value, port) => {
47
+ if (typeof value !== "string") return null
48
+ try {
49
+ const url = new URL(value)
50
+ return url.protocol === "http:" && ["127.0.0.1", "localhost"].includes(url.hostname) && url.port && Number(url.port) !== port && url.username === "" && url.password === "" ? url.origin : null
51
+ } catch {
52
+ return null
53
+ }
54
+ }
55
+
56
+ function studioFile(res, pathname) {
57
+ const [name, type] = STUDIO_FILES[pathname]
58
+ const file = join(STUDIO, name)
59
+ if (!existsSync(file)) return pathname === "/" ? page(res, "text/html; charset=utf-8", HOME_PAGE) : refuse(res, 404, "Not found.")
60
+ page(res, type, readFileSync(file))
61
+ }
62
+
63
+ const sha = (text) => createHash("sha256").update(text).digest("hex")
64
+
65
+ function json(res, status, value) {
66
+ res.writeHead(status, { ...HEADERS, "content-type": "application/json" })
67
+ res.end(JSON.stringify(value))
68
+ }
69
+
70
+ function page(res, type, body) {
71
+ res.writeHead(200, { ...HEADERS, "content-type": type })
72
+ res.end(body)
73
+ }
74
+
75
+ const refuse = (res, status, message) => json(res, status, { error: status, message })
76
+
77
+ async function readJson(req) {
78
+ const chunks = []
79
+ let size = 0
80
+ for await (const chunk of req) {
81
+ size += chunk.length
82
+ if (size > MAX_BODY) throw new EngineFailure("input", "too_large", "That request is too large.")
83
+ chunks.push(chunk)
84
+ }
85
+ if (size === 0) return {}
86
+ try {
87
+ return JSON.parse(Buffer.concat(chunks).toString())
88
+ } catch {
89
+ throw new EngineFailure("input", "bad_json", "That request isn't valid JSON.")
90
+ }
91
+ }
92
+
93
+ function sendFile(req, res, file) {
94
+ const { size } = statSync(file)
95
+ const type = TYPES[extname(file).toLowerCase()] ?? "application/octet-stream"
96
+ const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? "")
97
+ if (req.headers.range && !range) return refuse(res, 416, "Bad range.")
98
+ if (!range) {
99
+ res.writeHead(200, { ...HEADERS, "content-type": type, "content-length": size, "accept-ranges": "bytes" })
100
+ return createReadStream(file).pipe(res)
101
+ }
102
+ const start = range[1] === "" ? Math.max(0, size - Number(range[2])) : Number(range[1])
103
+ const end = range[1] !== "" && range[2] !== "" ? Math.min(Number(range[2]), size - 1) : size - 1
104
+ if (start > end) {
105
+ res.writeHead(416, { ...HEADERS, "content-range": `bytes */${size}` })
106
+ return res.end()
107
+ }
108
+ res.writeHead(206, { ...HEADERS, "content-type": type, "content-length": end - start + 1, "content-range": `bytes ${start}-${end}/${size}`, "accept-ranges": "bytes" })
109
+ createReadStream(file, { start, end }).pipe(res)
110
+ }
111
+
112
+ const statusOf = (error) => ({ outside_project: 403, missing_file: 404, exists: 409, too_large: 413, empty: 409 })[error.reason] ?? 400
113
+
114
+ /**
115
+ * @param {{ home: string, roots: string[], projects: object, jobs: object, tools: () => Promise<object>, tokenTtlMs: number, port: () => number, onActivity: (inFlight?: number) => void, onStop: () => void, sse: Set<object>, log: (line: string) => void, pid: number }} options
116
+ */
117
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
118
+
119
+ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid }) {
120
+ const tokens = new Map() // sha256 of a launch token → { expires, back }
121
+ const sessions = new Set()
122
+ const mediaSecret = randomBytes(32)
123
+ const media = new Map() // opaque id → { project, asset }
124
+
125
+ const mediaId = (projectId, assetId) => {
126
+ const id = createHmac("sha256", mediaSecret).update(`${projectId}:${assetId}`).digest("hex").slice(0, 32)
127
+ media.set(id, { project: projectId, asset: assetId })
128
+ return id
129
+ }
130
+
131
+ // offline: the file isn't where the project says, so the Studio asks to relink it (EG-3)
132
+ const withMedia = (state, asset) => ({ ...asset, media: mediaId(state.id, asset.id), ...(existsSync(isAbsolute(asset.path) ? asset.path : join(state.folder, asset.path)) ? {} : { offline: true }) })
133
+ const NOTICES = { index: "This project's index was damaged and set aside. Index the footage again.", journal: "This project's job record was damaged and set aside. Finished renders will be made again." }
134
+ const projectView = (state) => ({ project: state.log.current, head: state.log.head, assets: state.log.current.assets.map((asset) => withMedia(state, asset)), ...(state.damaged?.length ? { notices: state.damaged.map((part) => ({ kind: part === "index" ? "reindex" : "rerender", message: NOTICES[part] })) } : {}) })
135
+
136
+ function fenced(req) {
137
+ const allowed = [`127.0.0.1:${port()}`, `localhost:${port()}`]
138
+ if (!allowed.includes(req.headers.host)) return false
139
+ const { origin } = req.headers
140
+ if (origin && !allowed.some((host) => origin === `http://${host}`)) return false
141
+ const site = req.headers["sec-fetch-site"]
142
+ // Another port on 127.0.0.1 is the same site, so the Strict cookie would go with it:
143
+ // from there only a navigation (the harness's link) is let through (ES-11, ED17)
144
+ return site !== "cross-site" && (site !== "same-site" || req.headers["sec-fetch-mode"] === "navigate")
145
+ }
146
+
147
+ const hasSession = (req) => {
148
+ const cookie = (req.headers.cookie ?? "").split(/;\s*/).find((part) => part.startsWith(`${COOKIE}=`))
149
+ return !!cookie && sessions.has(sha(cookie.slice(COOKIE.length + 1)))
150
+ }
151
+
152
+ function openSession(req, res, { token }) {
153
+ const key = sha(String(token ?? ""))
154
+ const minted = tokens.get(key)
155
+ tokens.delete(key)
156
+ if (!minted || minted.expires < Date.now()) return refuse(res, 401, "This link has been used or has expired. Run kriya edit again.")
157
+ const session = randomBytes(32).toString("base64url")
158
+ sessions.add(sha(session))
159
+ log("a session opened")
160
+ res.writeHead(200, { ...HEADERS, "content-type": "application/json", "set-cookie": `${COOKIE}=${session}; HttpOnly; SameSite=Strict; Path=/` })
161
+ res.end(JSON.stringify({ back: minted.back }))
162
+ }
163
+
164
+ async function needProject(res, id) {
165
+ const state = /^[0-9a-f]{16}$/.test(id) ? await projects.get(id) : null
166
+ if (!state) refuse(res, 404, "There is no such project.")
167
+ return state
168
+ }
169
+
170
+ async function upload(req, res, state, url) {
171
+ const name = basename(url.searchParams.get("name") ?? "").replace(/[^\p{L}\p{N}._ -]+/gu, "-")
172
+ if (!name || name.startsWith(".")) return refuse(res, 400, "That file name can't be used.")
173
+ const dir = join(state.folder, "media")
174
+ mkdirSync(dir, { recursive: true })
175
+ const file = join(dir, name)
176
+ if (existsSync(file)) return refuse(res, 409, "A file with that name is already in this project.")
177
+ await pipeline(req, createWriteStream(file, { flags: "wx" }))
178
+ json(res, 200, withMedia(state, await projects.addAsset(state, file)))
179
+ }
180
+
181
+ function events(res) {
182
+ res.writeHead(200, { ...HEADERS, "content-type": "text/event-stream" })
183
+ res.write(": connected\n\n")
184
+ sse.add(res)
185
+ res.on("close", () => {
186
+ sse.delete(res)
187
+ onActivity()
188
+ })
189
+ }
190
+
191
+ async function assetFile(state, asset, kind) {
192
+ const { engine, log: history } = state
193
+ const found = history.current.assets.find((item) => item.id === asset)
194
+ if (kind === "peaks") return engine.peaks(asset)
195
+ if (kind === "thumbs") return engine.thumbs(asset)
196
+ if (found.kind === "video") return engine.proxy(asset)
197
+ return guardPath(isAbsolute(found.path) ? found.path : join(state.folder, found.path), [...roots, state.folder])
198
+ }
199
+
200
+ async function route(req, res, url) {
201
+ const { method } = req
202
+ const { pathname } = url
203
+ const parts = pathname.split("/").filter(Boolean)
204
+ const say = (status, value) => json(res, status, value)
205
+
206
+ if (method === "GET" && pathname === "/host") {
207
+ const { version } = await tools()
208
+ const runtime = activeRuntime(home)
209
+ return say(200, { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null, projects: projects.list().length })
210
+ }
211
+ if (method === "GET" && pathname === "/events") return events(res)
212
+
213
+ if (method === "GET" && pathname === "/browse") {
214
+ const root = guardPath(url.searchParams.get("root") ?? roots[0], roots)
215
+ const entries = readdirSync(root, { withFileTypes: true })
216
+ .filter((item) => !item.name.startsWith("."))
217
+ .map((item) => ({ name: item.name, kind: item.isDirectory() ? "folder" : item.isFile() ? "file" : "other" }))
218
+ return say(200, { root, entries })
219
+ }
220
+
221
+ // The person's own screen. Never on the socket, so nothing but a Studio session can
222
+ // say yes to a rule (ET-TST-01): no tool, no daemon, no job
223
+ if (parts[0] === "taste" && parts.length === 1 && method === "GET") return say(200, projects.taste.list())
224
+ if (parts[0] === "taste" && parts.length === 3 && method === "POST") {
225
+ const key = decodeURIComponent(parts[1])
226
+ const act = { confirm: projects.taste.confirm, dismiss: projects.taste.dismiss, remove: projects.taste.remove }[parts[2]]
227
+ if (!act || !act(key)) return refuse(res, 404, "That rule isn't there.")
228
+ return say(200, projects.taste.list())
229
+ }
230
+ if (parts[0] === "media" && parts.length === 2 && method === "GET") {
231
+ const found = media.get(parts[1])
232
+ if (!found) return refuse(res, 404, "Not found.")
233
+ return sendFile(req, res, await assetFile(await projects.get(found.project), found.asset))
234
+ }
235
+ if (parts[0] === "tiles" && parts.length === 2 && method === "GET") {
236
+ const found = media.get(parts[1])
237
+ const kind = url.searchParams.get("kind")
238
+ if (!found || !["peaks", "thumbs"].includes(kind)) return refuse(res, 404, "Not found.")
239
+ return sendFile(req, res, await assetFile(await projects.get(found.project), found.asset, kind))
240
+ }
241
+
242
+ if (parts[0] === "projects") {
243
+ if (parts.length === 1 && method === "GET") return say(200, { projects: projects.list().map(({ id, name }) => ({ id, name })) })
244
+ if (parts.length === 1 && method === "POST") {
245
+ const { name, folder } = await readJson(req)
246
+ if (typeof name !== "string" || !name.trim() || typeof folder !== "string") return refuse(res, 400, "A project needs a name and a folder.")
247
+ const state = await projects.create({ name, folder })
248
+ return say(200, { id: state.id })
249
+ }
250
+ const state = await needProject(res, parts[1])
251
+ if (!state) return
252
+ if (parts.length === 2 && method === "GET") return say(200, projectView(state))
253
+ if (parts.length === 2 && method === "PATCH") {
254
+ const { ops, undo } = await readJson(req)
255
+ if (undo === true) {
256
+ projects.undo(state)
257
+ return say(200, { ...projectView(state), diagnostics: [] })
258
+ }
259
+ const result = projects.change(state, { ops, author: "person" })
260
+ return say(result.ok ? 200 : 422, { ...projectView(state), diagnostics: result.diagnostics })
261
+ }
262
+ if (parts[2] === "assets" && method === "POST") {
263
+ const { path } = await readJson(req)
264
+ if (typeof path !== "string") return refuse(res, 400, "Give the file's path.")
265
+ return say(200, withMedia(state, await projects.addAsset(state, path)))
266
+ }
267
+ if (parts[2] === "upload" && method === "POST") return upload(req, res, state, url)
268
+ if (parts[2] === "plan" && method === "GET") {
269
+ const { version } = await tools()
270
+ // The solver's timeline too: the Studio's monitor and timeline place clips from it
271
+ const { picture, audio, overlays, captions, duration } = solve(state.log.current, state.index)
272
+ return say(200, { ...compile(state.log.current, state.index, { engineVersion: ENGINE_VERSION, runtimeVersion: version }), timeline: { picture, audio, overlays, captions, duration } })
273
+ }
274
+ if (parts[2] === "ask" && parts.length === 3 && method === "POST") {
275
+ const { text, selection } = await readJson(req)
276
+ if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want changed, in up to 2,000 characters.")
277
+ return say(200, await projects.ask(state, { text, selection }))
278
+ }
279
+ if (parts[2] === "proposals" && parts.length === 4 && method === "POST") {
280
+ const { accept, only } = await readJson(req)
281
+ if (typeof accept !== "boolean" || (only !== undefined && !(Array.isArray(only) && only.every(Number.isInteger)))) return refuse(res, 400, "Accept or reject the proposal.")
282
+ const result = projects.decide(state, parts[3], { accept, only })
283
+ return say(200, { ...result, ...projectView(state) })
284
+ }
285
+ if (parts[2] === "make" && parts.length === 3 && method === "POST") {
286
+ const { asset, brief } = await readJson(req)
287
+ const clean = {}
288
+ if (brief && typeof brief === "object") {
289
+ if (Number.isFinite(brief.seconds) && brief.seconds >= 5 && brief.seconds <= 600) clean.targetDuration = Math.round(brief.seconds * 705_600_000)
290
+ if (Array.isArray(brief.mustKeep) && brief.mustKeep.every((id) => typeof id === "string" && id.length < 64)) clean.mustKeep = brief.mustKeep.slice(0, 20)
291
+ if (brief.effort === "fast" || brief.effort === "best") clean.effort = brief.effort
292
+ if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
293
+ if (typeof brief.music === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.music)) clean.music = brief.music
294
+ }
295
+ if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
296
+ return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
297
+ }
298
+ if (parts[2] === "export" && parts[3] === "handoff" && parts.length === 4 && method === "POST") return say(200, projects.handoff(state))
299
+ if (parts[2] === "index" && parts.length === 3 && method === "GET") {
300
+ const { words, sentences, takes, shots } = state.index
301
+ return say(200, { assets: projects.indexStatus(state), words, sentences, takes, shots })
302
+ }
303
+ if (parts[2] === "index" && parts.length === 3 && method === "POST") {
304
+ const { asset } = await readJson(req)
305
+ if (typeof asset !== "string" || !state.log.current.assets.some((item) => item.id === asset)) return refuse(res, 400, "Name an asset in this project.")
306
+ return say(200, jobs.start(state, { kind: "index", asset }))
307
+ }
308
+ }
309
+
310
+ if (parts[0] === "jobs") {
311
+ if (method === "GET" && parts.length === 1) return say(200, { jobs: await jobs.list() })
312
+ if (method === "POST" && parts.length === 1) {
313
+ const { project, quality, deliverable } = await readJson(req)
314
+ if (!["draft", "master"].includes(quality)) return refuse(res, 400, "A job's quality is draft or master.")
315
+ const state = await needProject(res, project)
316
+ if (!state) return
317
+ return say(200, jobs.start(state, { quality, ...(deliverable ? { deliverable } : {}) }))
318
+ }
319
+ if (method === "DELETE" && parts.length === 2) return jobs.cancel(parts[1]) ? say(200, {}) : refuse(res, 404, "That job isn't running.")
320
+ // `kriya edit replay <job>`: a new job that repeats a finished make from its recording
321
+ if (method === "POST" && parts.length === 3 && parts[2] === "replay") {
322
+ const match = /^([0-9a-f]{16})\.(\d+)$/.exec(parts[1])
323
+ if (!match) return refuse(res, 400, "A job id looks like <project>.<number>.")
324
+ const state = await needProject(res, match[1])
325
+ if (!state) return
326
+ return say(200, jobs.start(state, { kind: "replay", of: Number(match[2]) }))
327
+ }
328
+ }
329
+ refuse(res, 404, "Not found.")
330
+ }
331
+
332
+ function mintToken(back = null) {
333
+ const token = randomBytes(32).toString("base64url")
334
+ tokens.set(sha(token), { expires: Date.now() + tokenTtlMs, back: backOf(back, port()) })
335
+ return token
336
+ }
337
+
338
+ /** @param {boolean} overSocket the socket is owner-only, so it needs no fence or session */
339
+ return async function handle(req, res, overSocket) {
340
+ onActivity(1)
341
+ const url = new URL(req.url, "http://host")
342
+ try {
343
+ if (overSocket) {
344
+ if (url.pathname === "/internal/info") return json(res, 200, { pid, port: port() })
345
+ if (url.pathname === "/internal/launch" && req.method === "POST") {
346
+ const token = mintToken((await readJson(req)).back)
347
+ return json(res, 200, { token, url: `http://127.0.0.1:${port()}/launch#${token}` })
348
+ }
349
+ // The harness says a person is working there: the Governor leaves room (EDIT_LOOP §8)
350
+ if (url.pathname === "/internal/live" && req.method === "POST") {
351
+ onLive()
352
+ return json(res, 200, {})
353
+ }
354
+ // The daemon's handover of a job from Kriya, and Kriya's cancel (EH-02, EH-03)
355
+ if (url.pathname === "/internal/job" && req.method === "POST") {
356
+ const body = await readJson(req)
357
+ const valid = UUID.test(body.dispatch) && UUID.test(body.job) && typeof body.folder === "string" && typeof body.brief === "string" && body.brief.length > 0 && body.brief.length <= 4000 && ["fast", "best"].includes(body.effort)
358
+ if (!valid) return refuse(res, 400, "That job isn't complete.")
359
+ return json(res, 200, await tavi.accept(body))
360
+ }
361
+ if (url.pathname === "/internal/cancel" && req.method === "POST") {
362
+ const { dispatch } = await readJson(req)
363
+ return json(res, 200, { known: UUID.test(dispatch) && tavi.cancel({ dispatch }) })
364
+ }
365
+ if (url.pathname === "/internal/stop" && req.method === "POST") {
366
+ json(res, 200, {})
367
+ return onStop()
368
+ }
369
+ if (url.pathname.startsWith("/taste")) return refuse(res, 403, "Only the person can change their rules, in the Studio.")
370
+ return await route(req, res, url)
371
+ }
372
+ if (!fenced(req)) return refuse(res, 403, "Not from here.")
373
+ // The app's own files carry nothing private; what they ask for needs the session
374
+ if (req.method === "GET" && Object.hasOwn(STUDIO_FILES, url.pathname)) return studioFile(res, url.pathname)
375
+ if (req.method === "GET" && url.pathname === "/launch") return page(res, "text/html; charset=utf-8", LAUNCH_PAGE)
376
+ if (req.method === "GET" && url.pathname === "/launch.js") return page(res, "text/javascript", LAUNCH_SCRIPT)
377
+ if (req.method === "POST" && url.pathname === "/session") return openSession(req, res, await readJson(req))
378
+ if (url.pathname.startsWith("/internal/")) return refuse(res, 404, "Not found.")
379
+ if (!hasSession(req)) return refuse(res, 401, "Open the Studio from Kriya.")
380
+ await route(req, res, url)
381
+ } catch (error) {
382
+ if (res.headersSent) return res.destroy()
383
+ if (error instanceof EngineFailure) return refuse(res, statusOf(error), error.message)
384
+ log(`request failed: ${error.name}`)
385
+ refuse(res, 500, "Something went wrong.")
386
+ } finally {
387
+ onActivity(-1)
388
+ }
389
+ }
390
+ }
391
+
@@ -0,0 +1,135 @@
1
+ // The taste ledger (DIRECTOR_AND_AGENT §12, EDD-31): how this person edits, from what they
2
+ // do. Code writes it and code aggregates it; a pattern seen across projects becomes a
3
+ // proposal, asked once; only the person confirms one, and only confirmed rules change
4
+ // anything. It lives on this computer, outside every project.
5
+
6
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
7
+ import { dirname, join } from "node:path"
8
+
9
+ import { editHome } from "./paths.js"
10
+
11
+ const REPEATS = 2 // At least twice, as Loop v2's rules do, and in different projects
12
+ const SIGNALS_MAX = 500
13
+ const ZOOM_STEP = 0.05
14
+
15
+ // What can be learned so far: only what a make job can then use (`defaults` below)
16
+ const KINDS = {
17
+ caption_look: {
18
+ read: (op) => (op.op === "caption_style" && typeof op.look === "string" ? op.look : null),
19
+ valid: (value) => typeof value === "string" && /^[a-z0-9-]{1,40}$/.test(value),
20
+ sentence: (value) => `You usually use the ${value} captions. Use them by default?`,
21
+ shown: (value) => `Captions: ${value}`,
22
+ },
23
+ zoom: {
24
+ read: (op) => (op.op === "punch_in" && Number.isFinite(op.scale) ? Math.round(op.scale / ZOOM_STEP) * ZOOM_STEP : null),
25
+ valid: (value) => Number.isFinite(value) && value > 1 && value <= 3,
26
+ sentence: (value) => `You usually zoom in to ${value.toFixed(2)}×. Use that by default?`,
27
+ shown: (value) => `Zoom: ${value.toFixed(2)}×`,
28
+ },
29
+ }
30
+
31
+ const keyOf = (kind, value) => `${kind}:${typeof value === "number" ? value.toFixed(2) : value}`
32
+
33
+ const fileOf = (home) => join(editHome(home), "taste.json")
34
+
35
+ /** What a person's accepted operations say, by kind. Nothing else is kept. */
36
+ export const signalsOf = (ops) =>
37
+ ops.flatMap((op) =>
38
+ Object.entries(KINDS).flatMap(([kind, { read, valid }]) => {
39
+ const value = read(op)
40
+ return value !== null && valid(value) ? [{ kind, value }] : []
41
+ })
42
+ )
43
+
44
+ export function createTaste({ home, now = () => new Date().toISOString() }) {
45
+ const read = () => {
46
+ try {
47
+ const kept = JSON.parse(readFileSync(fileOf(home), "utf8"))
48
+ return { signals: Array.isArray(kept.signals) ? kept.signals : [], rules: kept.rules && typeof kept.rules === "object" ? kept.rules : {} }
49
+ } catch {
50
+ return { signals: [], rules: {} }
51
+ }
52
+ }
53
+ const write = (ledger) => {
54
+ const file = fileOf(home)
55
+ mkdirSync(dirname(file), { recursive: true })
56
+ const temporary = `${file}.tmp`
57
+ writeFileSync(temporary, JSON.stringify(ledger), { mode: 0o600 })
58
+ renameSync(temporary, file)
59
+ }
60
+ const view = ([key, rule]) => ({ key, kind: rule.kind, value: rule.value, status: rule.status, sentence: KINDS[rule.kind].sentence(rule.value), shown: KINDS[rule.kind].shown(rule.value) })
61
+ const known = (rule) => KINDS[rule?.kind]?.valid(rule.value)
62
+
63
+ // A value seen in enough projects, with no answer yet, becomes one proposal
64
+ function propose(ledger) {
65
+ const seen = new Map()
66
+ for (const { kind, value, project } of ledger.signals) {
67
+ const key = keyOf(kind, value)
68
+ if (!seen.has(key)) seen.set(key, { kind, value, count: 0, projects: new Set() })
69
+ const group = seen.get(key)
70
+ group.count++
71
+ group.projects.add(project)
72
+ }
73
+ for (const [key, group] of seen) {
74
+ if (group.count >= REPEATS && group.projects.size >= REPEATS && !ledger.rules[key]) ledger.rules[key] = { kind: group.kind, value: group.value, status: "proposed", at: now() }
75
+ }
76
+ }
77
+
78
+ const decide = (key, status) => {
79
+ const ledger = read()
80
+ const rule = ledger.rules[key]
81
+ if (!known(rule)) return false
82
+ // One rule per kind: the newest thing the person said yes to
83
+ if (status === "confirmed") for (const other of Object.values(ledger.rules)) if (other.kind === rule.kind && other.status === "confirmed") other.status = "dismissed"
84
+ rule.status = status
85
+ rule.at = now()
86
+ write(ledger)
87
+ return true
88
+ }
89
+
90
+ return {
91
+ /** The person's own edit, or a proposal they accepted. Never a job's own operations. */
92
+ note(project, ops, entry) {
93
+ const found = signalsOf(ops)
94
+ if (!found.length) return
95
+ const ledger = read()
96
+ ledger.signals.push(...found.map((signal) => ({ ...signal, project, entry })))
97
+ ledger.signals = ledger.signals.slice(-SIGNALS_MAX)
98
+ propose(ledger)
99
+ write(ledger)
100
+ },
101
+ /** They undid it: it never happened, as far as taste goes. */
102
+ forget(project, entry) {
103
+ const ledger = read()
104
+ const left = ledger.signals.filter((s) => !(s.project === project && s.entry === entry))
105
+ if (left.length !== ledger.signals.length) write({ ...ledger, signals: left })
106
+ },
107
+ list() {
108
+ const rules = Object.entries(read().rules).filter(([, rule]) => known(rule)).map(view)
109
+ return { proposed: rules.filter((r) => r.status === "proposed"), confirmed: rules.filter((r) => r.status === "confirmed") }
110
+ },
111
+ confirm: (key) => decide(key, "confirmed"),
112
+ dismiss: (key) => decide(key, "dismissed"),
113
+ /** Removed from the one screen: it stops applying, and isn't asked about again. */
114
+ remove: (key) => decide(key, "dismissed"),
115
+ /** One proposal for the phone, once. */
116
+ nextToAsk() {
117
+ const ledger = read()
118
+ const found = Object.entries(ledger.rules).find(([, rule]) => rule.status === "proposed" && !rule.asked && known(rule))
119
+ if (!found) return null
120
+ found[1].asked = true
121
+ write(ledger)
122
+ return view(found)
123
+ },
124
+ /** Only confirmed rules, as a make job's defaults; what the brief says always wins. */
125
+ defaults() {
126
+ const out = {}
127
+ for (const rule of Object.values(read().rules)) {
128
+ if (rule.status !== "confirmed" || !known(rule)) continue
129
+ if (rule.kind === "caption_look") out.captions = rule.value
130
+ if (rule.kind === "zoom") out.zoom = rule.value
131
+ }
132
+ return out
133
+ },
134
+ }
135
+ }