@kriya-ai/harness 0.2.0 → 0.2.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kriya-ai/harness",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Kriya Harness (beta): a Kriya agent on your machine, built on DeepSeek Harness",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -54,11 +54,37 @@ export function schemaErrors(schema, value, path = "$") {
54
54
  return problems
55
55
  }
56
56
 
57
- const parse = (text) => {
57
+ /**
58
+ * The JSON in a reply: the whole text, or else the first complete object in it, so a
59
+ * thinking block, a fence or a sentence around it doesn't sink a good answer.
60
+ * A reply cut off by its output limit says so, since "too long" is what to fix.
61
+ */
62
+ export function parseReply(text, finish) {
63
+ const raw = String(text ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim()
58
64
  try {
59
- return { value: JSON.parse(String(text ?? "").replace(/^```(?:json)?\s*|\s*```$/g, "")) }
65
+ return { value: JSON.parse(raw.replace(/^```(?:json)?\s*|\s*```$/g, "")) }
60
66
  } catch {
61
- return { problem: "isn't valid JSON" }
67
+ // The first balanced {...}, skipping braces inside strings
68
+ for (let start = raw.indexOf("{"); start !== -1; start = raw.indexOf("{", start + 1)) {
69
+ let depth = 0
70
+ let quoted = false
71
+ for (let i = start; i < raw.length; i++) {
72
+ const c = raw[i]
73
+ if (quoted) {
74
+ if (c === "\\") i++
75
+ else if (c === '"') quoted = false
76
+ } else if (c === '"') quoted = true
77
+ else if (c === "{") depth++
78
+ else if (c === "}" && --depth === 0) {
79
+ try {
80
+ return { value: JSON.parse(raw.slice(start, i + 1)) }
81
+ } catch {
82
+ break
83
+ }
84
+ }
85
+ }
86
+ }
87
+ return { problem: finish === "length" || !raw ? "was cut off before it finished (too long)" : "isn't valid JSON" }
62
88
  }
63
89
  }
64
90
 
@@ -67,6 +93,8 @@ const parse = (text) => {
67
93
  */
68
94
  // One slot's wait: a call's own limit (120 s, director/gateway.js) and a little queue
69
95
  export const SLOT_WAIT_MS = 150_000
96
+ // Room for a reasoning model's thinking on top of the answer's own budget
97
+ export const THINKING = 1500
70
98
 
71
99
  export function createAsk({ governor, record = () => {}, budget = { take: () => true }, slotWaitMs = SLOT_WAIT_MS }) {
72
100
  // The gateway has been refusing this job for as long as a slot will wait: its other slots
@@ -91,7 +119,9 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
91
119
  const limit = AbortSignal.timeout(slotWaitMs)
92
120
  try {
93
121
  calls++
94
- reply = await governor.call({ model: tier, messages, response_format: { type: "json_schema", json_schema: { name: task, strict: false, schema } } }, { maxTokens: maxOutput, priority, signal: signal ? AbortSignal.any([signal, limit]) : limit })
122
+ // Low reasoning effort: a thinking model spends its output limit thinking otherwise,
123
+ // and answers with nothing (found in use: every console call ended at its 800 tokens)
124
+ reply = await governor.call({ model: tier, messages, response_format: { type: "json_schema", json_schema: { name: task, strict: false, schema } }, reasoning: { effort: "low" } }, { maxTokens: maxOutput + THINKING, priority, signal: signal ? AbortSignal.any([signal, limit]) : limit })
95
125
  } catch (error) {
96
126
  if (signal?.aborted) throw error
97
127
  if (limit.aborted) {
@@ -100,17 +130,17 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
100
130
  return { value: fallback(), source: "default", reason: "The model wasn't available for this job.", calls }
101
131
  }
102
132
  record({ task, tier, ms: Date.now() - started, result: `error:${error.code ?? error.status ?? "unknown"}` })
103
- return { value: fallback(), source: "default", reason: `The model couldn't answer (${error.code ?? error.message}).`, calls }
133
+ return { value: fallback(), source: "default", reason: `The model couldn't answer: ${String(error.message || error.code || "unknown").replace(/\.$/, "")}.`, calls }
104
134
  }
105
135
  const usage = reply?.usage ?? {}
106
136
  const content = reply?.choices?.[0]?.message?.content
107
- const parsed = parse(content)
137
+ const parsed = parseReply(content, reply?.choices?.[0]?.finish_reason)
108
138
  const problems = parsed.problem ? [parsed.problem] : [...schemaErrors(schema, parsed.value), ...(schemaErrors(schema, parsed.value).length ? [] : check(parsed.value))]
109
139
  record({ task, tier, input_tokens: usage.prompt_tokens ?? null, cached_tokens: usage.prompt_tokens_details?.cached_tokens ?? null, output_tokens: usage.completion_tokens ?? null, ms: Date.now() - started, result: problems.length ? "invalid" : attempt ? "repaired" : "ok" })
110
140
  if (!problems.length) return { value: parsed.value, source: attempt ? "repaired" : "model", calls }
111
141
  if (attempt === 0) {
112
142
  // One repair, with the exact reasons
113
- messages.push({ role: "assistant", content: String(content ?? "") }, { role: "user", content: `That answer was refused: ${problems.slice(0, 5).join("; ")}. Answer again with JSON that fits the schema, using only ids you were shown.` })
143
+ messages.push({ role: "assistant", content: String(content ?? "") }, { role: "user", content: `That answer was refused: ${problems.slice(0, 5).join("; ")}. Answer again with only the JSON that fits the schema, shorter if you can, using only ids you were shown. No explanation, no thinking aloud.` })
114
144
  continue
115
145
  }
116
146
  return { value: fallback(), source: "default", reason: `The model's answer didn't fit, twice: ${problems[0]}.`, calls }
@@ -60,11 +60,27 @@ export const OPS_SCHEMA = {
60
60
  additionalProperties: false,
61
61
  },
62
62
  },
63
+ // Words the recogniser got wrong, when the person asks to fix the transcript
64
+ corrections: {
65
+ type: "array",
66
+ maxItems: 40,
67
+ items: { type: "object", properties: { word: ID, text: { type: "string", maxLength: 60 } }, required: ["word", "text"], additionalProperties: false },
68
+ },
69
+ // A request about the whole video ("make it stunning", "edit all of it"): the Director's make job does that
70
+ direct: {
71
+ anyOf: [
72
+ { type: "null" },
73
+ { type: "object", properties: { seconds: { type: "integer", minimum: 5, maximum: 600 }, captions: { type: "string", enum: ["clean", "karaoke", "boxed"] } }, additionalProperties: false },
74
+ ],
75
+ },
63
76
  },
64
77
  required: ["ops"],
65
78
  additionalProperties: false,
66
79
  }
67
80
 
81
+ /** A correction's text: one word or a short name, no markup or line breaks. */
82
+ export const cleanWord = (text) => (typeof text === "string" ? text.replace(/[\u0000-\u001f<>]/g, "").trim().slice(0, 60) : "")
83
+
68
84
  const seconds = (flicks) => `${(flicks / FLICKS).toFixed(2)} s`
69
85
 
70
86
  /** What one operation did, in plain words, from the operation and the index only (track-A rule 7). */
@@ -114,6 +130,8 @@ export function describe(op, index) {
114
130
  return op.fit ? "Fitted the music to the cut on its downbeats" : "Shaped the music's fades"
115
131
  case "duck":
116
132
  return "Ducked the music under the speech"
133
+ case "add_deliverable":
134
+ return `Set up the export: ${op.size?.width ?? "?"}×${op.size?.height ?? "?"}${op.loudness ? `, mastered to ${op.loudness.lufs} LUFS` : ""}${op.burnCaptions ? ", captions burned in" : ""}`
117
135
  default:
118
136
  return op.op
119
137
  }
@@ -173,14 +191,34 @@ function clipsView(project, index) {
173
191
  export async function revise({ ask, project, index, text, selection, signal }) {
174
192
  const assets = project.assets.map((a) => a.id)
175
193
  const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), clipsView(project, index), selectionText(selection, index)].join("\n\n")
176
- const request = `The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}\nAnswer with the operations that do exactly this, and nothing else. If it can't be done with these operations, answer {"ops": []}.`
194
+ const request = [
195
+ `The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
196
+ "Answer with JSON only. Put in `ops` the operations that do exactly what they ask, and nothing else.",
197
+ "If they ask to fix or correct the transcript (names, misheard words), put each wrong word in `corrections` as {word: its id, text: the right word}, only where you are confident from the context.",
198
+ "If they ask for the whole video to be made, directed, edited or improved (not one part of it), set `direct` to an object (with `seconds` and a caption look if they say so) and leave `ops` empty: the Director makes the whole cut.",
199
+ 'If none of these can do it, answer {"ops": []}.',
200
+ ].join("\n")
201
+ const words = new Map((index.words ?? []).map((w) => [w.id, w]))
202
+ // Operations must apply; a correction on an unknown word is only dropped, never worth a second call
177
203
  const check = ({ ops }) => {
178
204
  if (!ops.length) return []
179
205
  const tried = apply(project, ops, { index, author: "agent" })
180
206
  return tried.applied ? [] : tried.diagnostics.map((d) => `operation ${d.op + 1}: ${d.message}`)
181
207
  }
182
- const answer = await ask({ task: "console", tier: "budget", schema: OPS_SCHEMA, view, request, maxOutput: 800, check, fallback: () => ({ ops: [] }), signal, priority: 0 })
208
+ const answer = await ask({ task: "console", tier: "budget", schema: OPS_SCHEMA, view, request, maxOutput: 2000, check, fallback: () => ({ ops: [] }), signal, priority: 0 })
183
209
  const ops = answer.value.ops
184
210
  const tried = ops.length ? apply(project, ops, { index, author: "agent" }) : null
185
- return { ops: tried?.applied ? ops : [], changes: tried?.applied ? ops.map((op) => describe(op, index)) : [], project: tried?.applied ? tried.project : null, source: answer.source, reason: answer.reason, calls: answer.calls }
211
+ // A correction that changes nothing, or isn't a known word, isn't offered
212
+ const corrections = (answer.value.corrections ?? []).map((c) => ({ word: c.word, text: cleanWord(c.text) })).filter((c) => words.has(c.word) && c.text && c.text !== words.get(c.word).text)
213
+ const direct = answer.value.direct && typeof answer.value.direct === "object" ? answer.value.direct : null
214
+ return {
215
+ ops: tried?.applied ? ops : [],
216
+ changes: tried?.applied ? ops.map((op) => describe(op, index)) : [],
217
+ corrections: corrections.map((c) => ({ ...c, change: `Corrected "${words.get(c.word).text}" to "${c.text}"` })),
218
+ direct,
219
+ project: tried?.applied ? tried.project : null,
220
+ source: answer.source,
221
+ reason: answer.reason,
222
+ calls: answer.calls,
223
+ }
186
224
  }
@@ -14,7 +14,15 @@ export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
14
14
  const running = new Map() // "<project>.<n>" → AbortController
15
15
 
16
16
  const idOf = (state, number) => `${state.id}.${number}`
17
- const view = (state, row) => ({ id: idOf(state, row.id), project: state.id, kind: row.kind, status: row.status, progress: row.progress, error: row.error, output: row.dispatch })
17
+ const assetOf = (row) => {
18
+ try {
19
+ return JSON.parse(row.request ?? "{}").asset ?? null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+ // The asset of an index job, so the Studio's bin shows its progress on the right file
25
+ const view = (state, row) => ({ id: idOf(state, row.id), project: state.id, kind: row.kind, status: row.status, progress: row.progress, error: row.error, output: row.dispatch, ...(row.kind === "index" ? { asset: assetOf(row) } : {}) })
18
26
 
19
27
  async function run(state, number, request) {
20
28
  const id = idOf(state, number)
@@ -17,7 +17,7 @@ import { openJournal } from "../graph/journal.js"
17
17
  import { solve } from "../core/solver.js"
18
18
  import { createAsk } from "../director/ask.js"
19
19
  import { LOOKS } from "../engine/captions.js"
20
- import { cleanSelection, describe, noteWord, revise } from "../director/revise.js"
20
+ import { cleanSelection, cleanWord, describe, noteWord, revise } from "../director/revise.js"
21
21
  import { openIndexDb } from "../index/db.js"
22
22
  import { makeReel, rebase } from "../loop/make.js"
23
23
  import { runGates } from "../gates/index.js"
@@ -28,6 +28,7 @@ import { createIndexer, layersFor } from "../index/index.js"
28
28
  import { activeRuntime } from "../runtime/setup.js"
29
29
  import { editHome } from "./paths.js"
30
30
  import { createTaste } from "./taste.js"
31
+ import { extractDna } from "../engine/dna.js"
31
32
 
32
33
  function atomicWrite(file, text) {
33
34
  const part = `${file}.${process.pid}.tmp`
@@ -69,6 +70,7 @@ const kindOf = ({ width, hasAudio }) => (width ? "video" : hasAudio ? "audio" :
69
70
  /**
70
71
  * @param {{ home: string, roots: string[], scheduler: object, tools: () => Promise<{ capabilities: object, version: string }> }} options
71
72
  */
73
+ const FLICKS = 705_600_000
72
74
  // Director model calls a job may make (DIRECTOR_AND_AGENT §13, short form)
73
75
  const JOB_CALLS = 40
74
76
 
@@ -184,7 +186,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
184
186
  },
185
187
 
186
188
  /** Brings a file in by reference: probed, fingerprinted, never copied or written. */
187
- async addAsset(state, path) {
189
+ async addAsset(state, path, { reference = false } = {}) {
188
190
  const real = guardPath(path, [...roots, state.folder])
189
191
  // A .cube is a LUT (ED13): read and checked here, before FFmpeg ever sees it, never probed as media
190
192
  const lut = extname(real).toLowerCase() === ".cube"
@@ -199,7 +201,9 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
199
201
  const id = `a${state.log.current.assets.length + 1}`
200
202
  const within = relative(state.folder, real)
201
203
  const stored = within.startsWith("..") || isAbsolute(within) ? real : within.split(sep).join("/")
202
- const op = { op: "add_asset", id, kind: lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: "unknown", facts }
204
+ // A reference is measured for its style only (EDD-23); the person confirmed they may use it
205
+ if (reference && !facts.width) throw new EngineFailure("input", "refused", "A reference needs to be a video.")
206
+ const op = { op: "add_asset", id, kind: reference ? "reference" : lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: "unknown", ...(reference ? { rightsNote: "The person confirmed they may use it as a style reference." } : {}), facts }
203
207
  const result = change(state, { ops: [op], author: "code" })
204
208
  if (!result.ok) throw new EngineFailure("input", "refused", result.diagnostics[0].message)
205
209
  return state.log.current.assets.at(-1)
@@ -243,11 +247,14 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
243
247
  async ask(state, { text, selection, job = 0 }) {
244
248
  const chosen = cleanSelection(selection, state.log.current, state.index)
245
249
  const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen })
246
- if (!result.ops.length) return { proposal: null, source: result.source, reason: result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way." }
250
+ // A request about the whole video goes to the Director's make job; the Studio offers it
251
+ const direct = result.direct ? { brief: { ...(result.direct.seconds ? { seconds: result.direct.seconds } : {}), ...(result.direct.captions ? { captions: result.direct.captions } : {}) } } : null
252
+ if (!result.ops.length && !result.corrections.length) return { proposal: null, direct, source: result.source, reason: direct ? null : (result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way.") }
247
253
  const id = randomBytes(6).toString("hex")
248
- state.proposals.set(id, { ops: result.ops, head: state.log.head })
249
- const { picture, duration } = solve(result.project, state.index)
250
- return { proposal: { id, ops: result.ops, changes: result.changes, timeline: { picture, duration } }, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
254
+ state.proposals.set(id, { ops: result.ops, corrections: result.corrections, head: state.log.head })
255
+ const { picture, duration } = solve(result.project ?? state.log.current, state.index)
256
+ // Changes in one list, operations first, then corrections: "Only this" counts across both
257
+ return { proposal: { id, ops: result.ops, changes: [...result.changes, ...result.corrections.map((c) => c.change)], timeline: result.ops.length ? { picture, duration } : null }, direct, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
251
258
  },
252
259
 
253
260
  /** Accept all, accept some, or reject a proposal. Rebased onto HEAD; the person's own edits never move. */
@@ -257,6 +264,8 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
257
264
  state.proposals.delete(id)
258
265
  if (!accept) return { applied: 0, dropped: [] }
259
266
  const chosen = Array.isArray(only) ? proposal.ops.filter((_, i) => only.includes(i)) : proposal.ops
267
+ const fixes = (proposal.corrections ?? []).filter((_, i) => !Array.isArray(only) || only.includes(proposal.ops.length + i))
268
+ for (const fix of fixes) this.correctWord(state, fix.word, fix.text)
260
269
  const { ops, dropped } = rebase(state.log.current, chosen, state.index)
261
270
  if (ops.length) {
262
271
  const result = change(state, { ops, author: "agent" })
@@ -264,7 +273,17 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
264
273
  // Accepting a proposal is the person's choice
265
274
  taste.note(state.id, ops, state.log.head)
266
275
  }
267
- return { applied: ops.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
276
+ return { applied: ops.length + fixes.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
277
+ },
278
+
279
+ /** The person's fix of a misheard word; captions, the transcript and the Director read it from now on. */
280
+ correctWord(state, word, text) {
281
+ const clean = cleanWord(text)
282
+ const asset = typeof word === "string" ? word.split(":w")[0] : ""
283
+ if (!state.index.words.some((w) => w.id === word) || !state.indexDb.correct(asset, word, clean)) throw new EngineFailure("input", "unknown_word", "There's no such word in this project's transcript.")
284
+ state.index = state.indexDb.read()
285
+ state.engine.load(state.log.current, state.index)
286
+ return state.index.words.find((w) => w.id === word)
268
287
  },
269
288
 
270
289
  /** A make job: the reel recipe through the Edit Loop, checked by the gates. */
@@ -286,9 +305,32 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
286
305
  // replay uses what the job really used. Captions only where they can render
287
306
  const recorded = replay?.answers.find((a) => a.task === "brief_extra")
288
307
  const extra = recorded ? JSON.parse(recorded.value) : { ...taste.defaults(), ...(picks && { picks }) }
308
+ // A style reference (EDD-23): measured to numbers only, never placed on a track. Its
309
+ // pace sets how often the picture changes (punch-ins), and its captions turn ours on
310
+ const styled = []
311
+ let captionsFromReference = false
312
+ const reference = request.brief?.reference && state.log.current.assets.find((a) => a.id === request.brief.reference && a.kind === "reference")
313
+ if (reference && !replay) {
314
+ try {
315
+ const dna = await extractDna(sourcesOf(state)(reference.id), { signal })
316
+ const seconds = (request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS
317
+ if (dna.pace.median) {
318
+ extra.punches = Math.min(8, Math.max(1, Math.round(seconds / dna.pace.median / 2)))
319
+ styled.push(`Took the pace of your reference: its picture changes every ${dna.pace.median.toFixed(1)} s, so ${extra.punches} punch-ins`)
320
+ }
321
+ if (dna.captions.present && !request.brief.captions && !extra.captions && state.engine.motion()) {
322
+ extra.captions = "clean"
323
+ captionsFromReference = true
324
+ styled.push("Your reference has captions, so this cut has them too")
325
+ }
326
+ } catch (error) {
327
+ if (signal?.aborted) throw error
328
+ styled.push(`Your reference couldn't be measured (${error.message}), so its style wasn't used.`)
329
+ }
330
+ }
289
331
  if (extra.captions && (!Object.hasOwn(LOOKS, extra.captions) || !state.engine.motion())) delete extra.captions
290
332
  if (!replay && Object.keys(extra).length) state.journal.answer({ job, task: "brief_extra", source: "person", value: extra })
291
- const usedRules = [...(extra.captions && !request.brief?.captions ? [`Used your rule: ${extra.captions} captions`] : []), ...(extra.zoom && !request.brief?.zoom ? [`Used your rule: ${extra.zoom.toFixed(2)}× zoom`] : [])]
333
+ const usedRules = [...styled, ...(extra.captions && !request.brief?.captions && !captionsFromReference ? [`Used your rule: ${extra.captions} captions`] : []), ...(extra.zoom && !request.brief?.zoom ? [`Used your rule: ${extra.zoom.toFixed(2)}× zoom`] : [])]
292
334
  const stages = ["story", "check", "repair"]
293
335
  const run = runTool
294
336
  const work = join(dirOf(state.id), "cache", "gates")
@@ -13,6 +13,7 @@ import { LOOKS } from "../engine/captions.js"
13
13
  import { ENGINE_VERSION, guardPath } from "../engine/index.js"
14
14
  import { EngineFailure } from "../engine/tool.js"
15
15
  import { activeRuntime } from "../runtime/setup.js"
16
+ import { recogniser } from "../index/layers/words.js"
16
17
 
17
18
  const HEADERS = {
18
19
  "cross-origin-opener-policy": "same-origin",
@@ -133,6 +134,39 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
133
134
  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
135
  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
 
137
+ // The Media Runtime, installed from the Studio with its progress shown (the same signed
138
+ // manifest and checks as `kriya edit setup`): a first Index no longer looks like nothing happening
139
+ let setup = null
140
+ const runtimeView = () => {
141
+ const runtime = activeRuntime(home)
142
+ return { version: runtime?.version ?? null, speech: recogniser(runtime).missing ?? null, setup }
143
+ }
144
+ function startSetup() {
145
+ if (setup && !setup.finished) return runtimeView()
146
+ setup = { step: null, done: null, total: null, line: "Asking Kriya for the Media Runtime", error: null, finished: false }
147
+ const tell = () => {
148
+ for (const res of sse) res.write(`event: setup\ndata: ${JSON.stringify(setup)}\n\n`)
149
+ }
150
+ let told = 0
151
+ const run = async () => {
152
+ const [{ readDevice }, { fetchManifest }, { install }] = await Promise.all([import("../../store.js"), import("../runtime/fetch.js"), import("../runtime/setup.js")])
153
+ const device = readDevice()
154
+ if (!device) throw new Error("This computer isn't signed in to Kriya. Run kriya login, then try again.")
155
+ const say = (line) => ((setup.line = line), tell())
156
+ const progress = (at) => {
157
+ Object.assign(setup, at)
158
+ if (Date.now() - told > 250 || at.done === at.total) ((told = Date.now()), tell())
159
+ }
160
+ await install(await fetchManifest(device), { home, say, progress })
161
+ }
162
+ onActivity(1)
163
+ run().then(
164
+ () => Object.assign(setup, { finished: true, step: null, line: "The Media Runtime is ready." }),
165
+ (error) => Object.assign(setup, { finished: true, error: error.message }),
166
+ ).finally(() => (tell(), onActivity(-1)))
167
+ return runtimeView()
168
+ }
169
+
136
170
  function fenced(req) {
137
171
  const allowed = [`127.0.0.1:${port()}`, `localhost:${port()}`]
138
172
  if (!allowed.includes(req.headers.host)) return false
@@ -175,7 +209,8 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
175
209
  const file = join(dir, name)
176
210
  if (existsSync(file)) return refuse(res, 409, "A file with that name is already in this project.")
177
211
  await pipeline(req, createWriteStream(file, { flags: "wx" }))
178
- json(res, 200, withMedia(state, await projects.addAsset(state, file)))
212
+ // ?as=reference: the person confirmed in the Studio they may use it as a style reference
213
+ json(res, 200, withMedia(state, await projects.addAsset(state, file, { reference: url.searchParams.get("as") === "reference" })))
179
214
  }
180
215
 
181
216
  function events(res) {
@@ -220,6 +255,8 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
220
255
 
221
256
  // The person's own screen. Never on the socket, so nothing but a Studio session can
222
257
  // say yes to a rule (ET-TST-01): no tool, no daemon, no job
258
+ if (parts[0] === "runtime" && parts.length === 1 && method === "GET") return say(200, runtimeView())
259
+ if (parts[0] === "runtime" && parts[1] === "setup" && parts.length === 2 && method === "POST") return say(202, startSetup())
223
260
  if (parts[0] === "taste" && parts.length === 1 && method === "GET") return say(200, projects.taste.list())
224
261
  if (parts[0] === "taste" && parts.length === 3 && method === "POST") {
225
262
  const key = decodeURIComponent(parts[1])
@@ -291,10 +328,17 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
291
328
  if (brief.effort === "fast" || brief.effort === "best") clean.effort = brief.effort
292
329
  if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
293
330
  if (typeof brief.music === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.music)) clean.music = brief.music
331
+ if (typeof brief.reference === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.reference)) clean.reference = brief.reference
294
332
  }
295
333
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
296
334
  return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
297
335
  }
336
+ // The person fixes a word the recogniser misheard (UX_SPEC §5)
337
+ if (parts[2] === "words" && parts.length === 4 && method === "POST") {
338
+ const { text } = await readJson(req)
339
+ if (typeof text !== "string" || text.length > 60 || /[\n\r<>]/.test(text)) return refuse(res, 400, "Give the word as it should read, in up to 60 characters.")
340
+ return say(200, { word: projects.correctWord(state, decodeURIComponent(parts[3]), text) })
341
+ }
298
342
  if (parts[2] === "export" && parts[3] === "handoff" && parts.length === 4 && method === "POST") return say(200, projects.handoff(state))
299
343
  if (parts[2] === "index" && parts.length === 3 && method === "GET") {
300
344
  const { words, sentences, takes, shots } = state.index
@@ -69,14 +69,36 @@ export function openIndexDb(file) {
69
69
  })
70
70
  },
71
71
 
72
+ /**
73
+ * The person's fix of a misheard word. Kept by word id beside the recogniser's rows,
74
+ * which a re-index replaces; the word's original text is kept too, so a re-index
75
+ * that moves the words never lands a fix on a different word.
76
+ * Text equal to the recogniser's, or empty, removes the fix.
77
+ */
78
+ correct(asset, word, text) {
79
+ const media = mediaOf(asset)
80
+ const n = Number(word.slice(`${asset}:w`.length))
81
+ const row = media && word.startsWith(`${asset}:w`) && Number.isInteger(n) ? db.prepare("select text from words where media = ? and n = ?").get(media, n) : null
82
+ if (!row) return false
83
+ tx(() => {
84
+ db.prepare("delete from corrections where asset = ? and word = ?").run(asset, word)
85
+ if (text && text !== row.text) db.prepare("insert into corrections (asset, word, text, at) values (?, ?, ?, ?)").run(asset, word, JSON.stringify({ text, was: row.text }), new Date().toISOString())
86
+ })
87
+ return true
88
+ },
89
+
72
90
  /** Rows for Edit Core and the views, for these assets (DATA_MODEL §3.1 shapes, ids per asset). */
73
91
  read(assets = db.prepare("select asset from assets order by asset").all().map((row) => row.asset)) {
74
92
  const raw = { words: [], sentences: [], takes: [], shots: [], faces: [], silences: [], beats: [], bars: [], timestamps: {}, subjects: {} }
75
93
  for (const asset of assets) {
76
94
  const media = mediaOf(asset)
77
95
  if (!media) continue
96
+ const fixes = new Map(db.prepare("select word, text from corrections where asset = ?").all(asset).map((c) => [c.word, JSON.parse(c.text)]))
78
97
  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) })
98
+ const id = `${asset}:w${w.n}`
99
+ const fix = fixes.get(id)
100
+ const fixed = fix && fix.was === w.text
101
+ raw.words.push({ id, asset, start: w.start, end: w.end, text: fixed ? fix.text : w.text, conf: fixed ? 1 : w.conf, flags: flagList(w.flags).filter((f) => !fixed || f !== "low_confidence"), ...(fixed ? { heard: w.text } : {}) })
80
102
  }
81
103
  for (const s of db.prepare('select * from sentences where media = ? order by n').all(media)) {
82
104
  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 })
@@ -105,7 +105,7 @@ const STORY_SCHEMA = {
105
105
  required: ["hook", "drop"],
106
106
  additionalProperties: false,
107
107
  }
108
- const EMPHASIS_SCHEMA = { type: "object", properties: { emphasis: { type: "array", maxItems: 3, items: { type: "string", maxLength: 64 } } }, required: ["emphasis"], additionalProperties: false }
108
+ const EMPHASIS_SCHEMA = { type: "object", properties: { emphasis: { type: "array", maxItems: 8, items: { type: "string", maxLength: 64 } } }, required: ["emphasis"], additionalProperties: false }
109
109
 
110
110
  /**
111
111
  * Plans the reel as operations on `project` (which keeps its assets; its cut is replaced).
@@ -162,7 +162,8 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
162
162
  let step = apply(project, ops, { index, author: "agent" })
163
163
  if (!step.applied) throw new Error(`The reel's cut was refused: ${step.diagnostics[0].message}`)
164
164
 
165
- // Emphasis: a few words worth a punch-in
165
+ // Emphasis: a few words worth a punch-in; a reference's pace can ask for more (EDD-23)
166
+ const most = Number.isInteger(brief.punches) && brief.punches > 0 ? Math.min(brief.punches, 8) : recipe.punch.max
166
167
  const kept = chosen.flatMap((l) => runsOf(l).flat())
167
168
  const keptIds = new Set(kept.map((w) => w.id))
168
169
  const emphasis = await ask({
@@ -170,16 +171,16 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
170
171
  schema: EMPHASIS_SCHEMA,
171
172
  recipe: recipe.notes,
172
173
  view: paperEdit({ ...scoped, sentences: chosen }, { assets: [asset] }),
173
- request: `Pick up to ${recipe.punch.max} single words to emphasise with a quick zoom: numbers, names, the point of a line. Word ids only.`,
174
+ request: `Pick up to ${most} single words to emphasise with a quick zoom: numbers, names, the point of a line. Word ids only.`,
174
175
  maxOutput: 200,
175
176
  check: ({ emphasis: picked }) => picked.filter((id) => !keptIds.has(id)).map((id) => `"${id}" isn't a kept word`),
176
- fallback: () => ({ emphasis: kept.filter((w) => /\d/.test(w.text)).slice(0, recipe.punch.max).map((w) => w.id) }),
177
+ fallback: () => ({ emphasis: kept.filter((w) => /\d/.test(w.text)).slice(0, most).map((w) => w.id) }),
177
178
  signal,
178
179
  })
179
180
  calls += emphasis.calls
180
181
  slots.emphasis = emphasis.source
181
182
  if (emphasis.reason) notes.push(`Emphasis: ${emphasis.reason}`)
182
- const punches = [...new Set(emphasis.value.emphasis)].slice(0, recipe.punch.max).map((id) => ({ op: "punch_in", at: { word: id, edge: "start" }, until: { word: id, edge: "end" }, scale: brief.zoom ?? recipe.punch.scale }))
183
+ const punches = [...new Set(emphasis.value.emphasis)].slice(0, most).map((id) => ({ op: "punch_in", at: { word: id, edge: "start" }, until: { word: id, edge: "end" }, scale: brief.zoom ?? recipe.punch.scale }))
183
184
 
184
185
  // Reframe to 9:16: follow the speaker where the index has one, else hold the centre
185
186
  const facts = project.assets.find((a) => a.id === asset).facts
@@ -6,7 +6,7 @@ import { createHash, createPublicKey, verify } from "node:crypto"
6
6
  import { createReadStream } from "node:fs"
7
7
 
8
8
  /** Ed25519 public keys, base64 SPKI DER, from `npx tsx lib/editing/sign.ts keygen` in Kriya. */
9
- export const TRUSTED_KEYS = []
9
+ export const TRUSTED_KEYS = ["MCowBQYDK2VwAyEAOS8m+4bFVNmiA4Q/iM3osrmj/O2uShAD7lROZezQ6Rk="]
10
10
 
11
11
  export class RuntimeError extends Error {}
12
12
 
@@ -48,7 +48,7 @@ async function fetchFrom(artifact, offset) {
48
48
  }
49
49
 
50
50
  /** Downloads to `part`, resuming what's there. The hash decides; a wrong file is deleted. */
51
- async function download(artifact, part) {
51
+ async function download(artifact, part, onBytes = () => {}) {
52
52
  let offset = sizeOf(part)
53
53
  if (offset > artifact.bytes) {
54
54
  rmSync(part)
@@ -70,6 +70,7 @@ async function download(artifact, part) {
70
70
  break
71
71
  }
72
72
  if (!out.write(chunk)) await once(out, "drain")
73
+ onBytes(written)
73
74
  }
74
75
  } catch {
75
76
  cut = true
@@ -88,10 +89,11 @@ async function download(artifact, part) {
88
89
  }
89
90
  }
90
91
 
91
- async function placeArtifact(artifact, root, dir, home, say) {
92
+ async function placeArtifact(artifact, root, dir, home, say, progress = () => {}) {
92
93
  say(`Downloading ${artifact.id} ${artifact.version} (${(artifact.bytes / 1e6).toFixed(0)} MB)`)
93
94
  const part = join(root, ".downloads", `${artifact.sha256}.part`)
94
- await download(artifact, part)
95
+ progress({ step: artifact.id, done: sizeOf(part), total: artifact.bytes })
96
+ await download(artifact, part, (done) => progress({ step: artifact.id, done, total: artifact.bytes }))
95
97
  const target = join(dir, artifact.id)
96
98
  mkdirSync(target, { recursive: true })
97
99
  if (artifact.unpack === "zip") await runChild(home)("unzip", ["-q", "-o", part, "-d", target])
@@ -99,8 +101,9 @@ async function placeArtifact(artifact, root, dir, home, say) {
99
101
  rmSync(part)
100
102
  }
101
103
 
102
- async function placePython(python, dir, run, say) {
104
+ async function placePython(python, dir, run, say, progress) {
103
105
  say(`Installing the ${python.id} environment (Python ${python.version}, ${python.packages.length} packages)`)
106
+ progress({ step: python.id, done: null, total: null })
104
107
  const lock = join(dir, `${python.id}.lock`)
105
108
  writeFileSync(lock, python.requirements)
106
109
  const venv = join(dir, "python")
@@ -153,9 +156,10 @@ function use(root, version) {
153
156
 
154
157
  /**
155
158
  * @param {{ text: string, data: object }} opened from openManifest
156
- * @param {{ home?: string, platform?: string, run?: (command: string, args: string[]) => Promise<string>, free?: (dir: string) => number, say?: (line: string) => void }} [options]
159
+ * @param {{ home?: string, platform?: string, run?: (command: string, args: string[]) => Promise<string>, free?: (dir: string) => number, say?: (line: string) => void, progress?: (at: { step: string, done: number | null, total: number | null }) => void }} [options]
160
+ * progress: bytes of each download as they arrive, for the Studio's progress bar
157
161
  */
158
- export async function install({ text, data }, { home = kriyaHome(), platform = platformId(), run = runChild(home), free = freeBytes, say = () => {} } = {}) {
162
+ export async function install({ text, data }, { home = kriyaHome(), platform = platformId(), run = runChild(home), free = freeBytes, say = () => {}, progress = () => {} } = {}) {
159
163
  const spec = data.platforms[platform]
160
164
  if (!spec) throw new RuntimeError(`This runtime isn't available for this computer (${platform}) yet.`)
161
165
  refuseLicences(data)
@@ -183,8 +187,8 @@ export async function install({ text, data }, { home = kriyaHome(), platform = p
183
187
  rmSync(dir, { recursive: true, force: true })
184
188
  mkdirSync(dir, { recursive: true })
185
189
  try {
186
- for (const artifact of spec.artifacts) await placeArtifact(artifact, root, dir, home, say)
187
- await placePython(spec.python, dir, run, say)
190
+ for (const artifact of spec.artifacts) await placeArtifact(artifact, root, dir, home, say, progress)
191
+ await placePython(spec.python, dir, run, say, progress)
188
192
  writeFileSync(join(dir, "manifest.json"), text)
189
193
  writeFileSync(join(dir, ".complete"), hash)
190
194
  // The environment no longer needs it, and it's as big as the environment
@@ -73,6 +73,18 @@ a { color: var(--teal); }
73
73
  .btn[aria-pressed="true"] { box-shadow: inset 0 0 0 2px var(--teal); }
74
74
  .field { min-height: 44px; padding: 0 12px; border-radius: 10px; border: 0; background: var(--sheet); color: inherit; font: inherit; box-shadow: inset 0 0 0 1px var(--edge); width: 100%; }
75
75
  .field.small { width: auto; }
76
+ /* A select draws its own chevron, inset from the edge, so the arrow never sits on the border */
77
+ .field.select { appearance: none; -webkit-appearance: none; padding-right: 36px; background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%); background-position: calc(100% - 18px) 50%, calc(100% - 13px) 50%; background-size: 5px 5px, 5px 5px; background-repeat: no-repeat; cursor: pointer; }
78
+ .field.small.select { min-width: 132px; }
79
+ .btn.wide { width: 100%; }
80
+ .btn:disabled { opacity: 0.55; cursor: default; }
81
+ .note.small { font-size: 13px; }
82
+ .row.tight { flex-wrap: nowrap; }
83
+ .row.tight .field { flex: 1; min-width: 0; }
84
+ .progress { height: 6px; border-radius: 999px; background: var(--hover); overflow: hidden; margin: 4px 0; }
85
+ .progress span { display: block; height: 100%; background: var(--teal); border-radius: inherit; transition: width 0.2s; }
86
+ .progress span.busy { width: 35%; animation: busy 1.2s ease-in-out infinite; }
87
+ @keyframes busy { from { transform: translateX(-100%); } to { transform: translateX(300%); } }
76
88
  :focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
77
89
  .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
78
90
  .inline { display: inline-flex; gap: 6px; align-items: center; min-height: 44px; }
@@ -113,7 +125,7 @@ a { color: var(--teal); }
113
125
  .monitor { max-width: 100%; max-height: 62vh; background: #000; display: block; }
114
126
  .transport { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: 10px; }
115
127
  .area-monitor .chip { background: rgb(255 255 255 / 0.12); color: #ddd; }
116
- .area-monitor .field { background: #2a2a2a; color: #eee; }
128
+ .area-monitor .field { background-color: #2a2a2a; color: #eee; }
117
129
 
118
130
  .prompt { display: flex; gap: 8px; }
119
131
  .chip.selection { background: color-mix(in srgb, var(--teal) 16%, transparent); color: var(--ink); }
@@ -131,6 +143,9 @@ a { color: var(--teal); }
131
143
  .word.unsure { text-decoration: underline dotted var(--saffron); }
132
144
  .word.now { background: color-mix(in srgb, var(--saffron) 25%, transparent); }
133
145
  .word[aria-pressed="true"] { box-shadow: inset 0 0 0 2px var(--teal); }
146
+ .word.fixed { text-decoration: underline solid color-mix(in srgb, var(--teal) 60%, transparent); text-underline-offset: 4px; }
147
+ .word-edit { font: inherit; color: inherit; background: var(--paper); border: 0; border-radius: 6px; padding: 4px 6px; min-height: 32px; box-shadow: inset 0 0 0 2px var(--teal); }
148
+ .hint { margin-top: -4px; }
134
149
 
135
150
  .timeline { display: grid; grid-template-columns: 80px minmax(0, 1fr); grid-template-rows: auto auto; gap: 0 8px; }
136
151
  .lane-labels { display: grid; grid-auto-rows: 50px; font-size: 12px; color: var(--ink-2); align-items: center; }
@@ -144,6 +159,19 @@ a { color: var(--teal); }
144
159
 
145
160
  .bin { list-style: none; padding: 0; margin: 0 0 10px; display: grid; gap: 8px; }
146
161
  .asset { display: grid; gap: 4px; }
162
+ .refs { margin-top: 12px; }
163
+ .by-path { margin-top: 10px; }
164
+ .by-path summary { cursor: pointer; min-height: 44px; display: flex; align-items: center; color: var(--ink-2); font-size: 13px; }
165
+ .make { display: grid; gap: 8px; margin-bottom: 16px; }
166
+ .make-status:empty { display: none; }
167
+ .banner { padding: 8px 12px 0; display: grid; gap: 8px; }
168
+ .banner > .note { margin: 0; padding: 10px 14px; border-radius: 10px; background: color-mix(in srgb, var(--teal) 12%, transparent); color: var(--ink); }
169
+ .banner > .note:empty, .banner > [hidden] { display: none; }
170
+ .setup { box-shadow: inset 0 0 0 1px var(--teal); display: grid; gap: 6px; grid-template-columns: minmax(0, 1fr) auto; align-items: center; }
171
+ .setup h2, .setup > div { grid-column: 1 / -1; }
172
+ .setup > div:empty { display: none; }
173
+ .setup > p { margin: 0; }
174
+ .area-kriya h2 + .make { margin-top: 0; }
147
175
  .finish { display: grid; gap: 12px; }
148
176
  .scope-row { display: flex; gap: 10px; flex-wrap: wrap; }
149
177
  .scope-row figure { margin: 0; }
@@ -160,4 +188,4 @@ a { color: var(--teal); }
160
188
  .modes .btn { flex: 1; }
161
189
  .monitor { max-height: 50vh; }
162
190
  }
163
- @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
191
+ @media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
@@ -1 +1,3 @@
1
- function t(e,o={},...d){let i=document.createElement(e);for(let[l,n]of Object.entries(o??{}))n==null||n===!1||(l.startsWith("on")?i.addEventListener(l.slice(2),n):l==="class"?i.className=n:l==="dataset"?Object.assign(i.dataset,n):n===!0?i.setAttribute(l,""):i.setAttribute(l,String(n)));for(let l of d.flat())l!=null&&l!==!1&&i.append(l instanceof Node?l:String(l));return i}var U=e=>(e.replaceChildren(),e);async function F(e,o,d){let i=await fetch(o,{method:e,headers:d===void 0?{}:{"content-type":"application/json"},body:d===void 0?void 0:JSON.stringify(d),credentials:"same-origin"}),l=await i.json().catch(()=>({}));if(!i.ok){let n=new Error(l.message??`The Edit Host answered ${i.status}.`);throw n.status=i.status,n.value=l,n}return l}var Bt=(e,o,d)=>.2126*e+.7152*o+.0722*d;function Gt(e,o=128){let d=new Uint32Array(256),i=Array.from({length:o},()=>new Uint32Array(64)),{data:l,width:n,height:m}=e,h=Math.max(1,Math.floor(n*m/6e4));for(let c=0,u=0;u<n*m;u+=h,c=u*4){let y=Math.min(255,Math.round(Bt(l[c],l[c+1],l[c+2])));d[y]++,i[Math.min(o-1,Math.floor(u%n/n*o))][y>>2]++}return{histogram:d,waveform:i}}function $t({root:e,pixels:o,project:d}){let i=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma histogram"}),l=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma waveform"}),n=t("ul",{class:"jobs","aria-live":"polite"}),m=t("p",{class:"note",role:"status"}),h=async a=>{m.textContent="";try{await F("POST","/jobs",{project:d().id,quality:a}),C()}catch(b){m.textContent=b.message}},c=t("p",{class:"note",role:"status"}),u=t("ul",{class:"jobs","aria-label":"Handoff files"}),y=async()=>{c.textContent="",U(u);try{let a=await F("POST",`/projects/${d().id}/export/handoff`),b=a.chapters.length,x=b?`, ${b} chapter${b===1?"":"s"}`:"";c.textContent=`Written to ${a.folder}, with ${a.media} media file${a.media===1?"":"s"} linked${x}.`;for(let P of a.files)u.append(t("li",{},t("span",{class:"file"},P)));for(let P of a.omitted)u.append(t("li",{},t("span",{class:"label-mono"},P.format),` ${P.reason}`))}catch(a){c.textContent=a.message}};e.append(t("section",{class:"panel scopes","aria-label":"Scopes"},t("h2",{},"Scopes"),t("div",{class:"scope-row"},t("figure",{},i,t("figcaption",{},"Histogram")),t("figure",{},l,t("figcaption",{},"Waveform"))),t("p",{class:"note"},"Measured on the preview: 8-bit, from the proxy.")),t("section",{class:"panel export","aria-label":"Export"},t("h2",{},"Export"),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:()=>h("draft")},"Render a draft"),t("button",{type:"button",class:"btn primary",onclick:()=>h("master")},"Render the master")),t("p",{class:"note"},"Files go to the exports folder beside the project. Sources are never written."),m,n),t("section",{class:"panel handoff","aria-label":"Handoff"},t("h2",{},"Handoff"),t("p",{class:"note"},"For Premiere, Resolve or Final Cut: the cut as OTIO, FCPXML, EDL and SRT, with chapters, and the media linked beside them."),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:y},"Export for another editor")),c,u));function w(a,b){let x=a.getContext("2d");x.clearRect(0,0,a.width,a.height),x.fillStyle=getComputedStyle(e).getPropertyValue("--scope").trim()||"#6cc0b8",b(x)}function W(){let a=o();if(!a)return;let{histogram:b,waveform:x}=Gt(a),P=Math.max(1,...b);w(i,T=>b.forEach((E,_)=>T.fillRect(_,100-E/P*100,1,E/P*100))),w(l,T=>x.forEach((E,_)=>E.forEach((K,A)=>{K&&(T.globalAlpha=Math.min(1,.15+K/200),T.fillRect(_*2,100-A/64*100-2,2,2))})))}async function C(){let{jobs:a}=await F("GET","/jobs");U(n);for(let b of a.filter(x=>x.project===d().id&&x.kind==="render").reverse().slice(0,8)){let x=b.output?b.output.split(/[\\/]/).at(-1):null;n.append(t("li",{},t("span",{class:"label-mono"},b.status),` ${b.progress}%`,x?t("span",{class:"file"},` ${x}`):null,b.error?t("span",{class:"error"},` ${b.error}`):null))}}return{scopes:W,refresh:C}}var Ct=e=>typeof e=="number"?{n:e,d:1}:e??{n:1,d:1},jt=e=>[...e?.picture??[]].sort((o,d)=>o.at-d.at),ft=e=>[{clip:null,asset:e.id,in:0,out:e.facts.duration,at:0,end:e.facts.duration,speed:{n:1,d:1}}],tt=(e,o)=>e.find(d=>o>=d.at&&o<d.end)??(e.length&&o>=e.at(-1).end?e.at(-1):null);function Q(e,o){if(e.hold)return e.in;let{n:d,d:i}=Ct(e.speed);return Math.min(e.out,e.in+Math.round((o-e.at)*d/i))}function it(e,o,d){for(let i of e){if(i.asset!==o||i.hold||d<i.in||d>=i.out)continue;let{n:l,d:n}=Ct(i.speed);return i.at+Math.round((d-i.in)*n/l)}return null}var ct=e=>e.length?Math.max(...e.map(o=>o.end)):0;function Pt(e,o){let d=[];for(let i of o){let l=it(e,i.asset,i.start);l!==null&&l>0&&d.push({id:i.id,at:l})}return d}var Y=e=>7056e5*e.d/e.n,Tt=(e,o)=>Math.floor(e/Y(o)+1e-9),lt=(e,o)=>Math.round(Tt(e,o)*Y(o));function et(e,o){let d=Math.max(0,e)/7056e5,i=Math.floor(d/60),l=Math.floor(d%60),n=Tt(Math.max(0,e)-Math.floor(d)*7056e5,o);return`${String(i).padStart(2,"0")}:${String(l).padStart(2,"0")}.${String(n).padStart(2,"0")}`}function Et(e,{shift:o=!1,mod:d=!1}={}){if(d)return e==="z"||e==="Z"?{type:o?"redo":"undo"}:null;switch(e){case" ":return{type:"toggle"};case"k":case"K":return{type:"rate",rate:0};case"l":case"L":return{type:"faster"};case"j":case"J":return{type:"reverse"};case"ArrowRight":return{type:"step",frames:o?null:1,seconds:o?1:null};case"ArrowLeft":return{type:"step",frames:o?null:-1,seconds:o?-1:null};case"Home":return{type:"seek",t:0};case"1":return{type:"mode",mode:"direct"};case"2":return{type:"mode",mode:"edit"};case"3":return{type:"mode",mode:"finish"};case"/":return{type:"prompt"};case"s":case"S":return{type:"split"};case"Backspace":case"Delete":return{type:"delete"};default:return null}}function At(e,o,{fps:d,duration:i}){let l=Math.max(0,i-Y(d)),n=m=>Math.min(Math.max(0,Math.round(m)),l);switch(o.type){case"toggle":return{...e,rate:e.rate===0?1:0};case"rate":return{...e,rate:o.rate};case"faster":return{...e,rate:e.rate<=0?1:2};case"reverse":return{...e,rate:e.rate>=0?-1:-2};case"step":{let m=o.frames!==null?o.frames*Y(d):o.seconds*7056e5;return{rate:0,t:n(lt(e.t,d)+m)}}case"seek":return{...e,t:n(o.t)};case"tick":{let m=n(o.t);return{t:m,rate:m===0&&e.rate<0||m===l&&e.rate>0?0:e.rate}}default:return e}}var Ht=1280;function Ot({canvas:e,urlOf:o,assetOf:d,onTime:i,onRate:l}){let n=e.getContext("2d",{willReadFrequently:!0}),m=new Map,h=[],c={n:30,d:1},u=0,y=0,w=0,W={width:1920,height:1080},C=1,a=!1,b=0,x=null;function P(r){let f=h[r],v=`${f.asset}:${r%2}`;if(!m.has(v)){let S=document.createElement("video");Object.assign(S,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:o(f.asset)}),m.set(v,S)}return m.get(v)}function T(r,f){let v=d(r.asset)?.facts?.fps??c;return(f+Y(v)/2)/7056e5}function E(){let r=Math.min(1,Ht/Math.max(W.width,W.height)),f=Math.round(W.width*r),v=Math.round(W.height*r);(e.width!==f||e.height!==v)&&Object.assign(e,{width:f,height:v})}function _(r,f,v){E();let{width:S,height:N}=e;if(n.fillStyle="#000",n.fillRect(0,0,S,N),r?.videoWidth){let $=Math.max(S/r.videoWidth,N/r.videoHeight)*C,L=r.videoWidth*$,Z=r.videoHeight*$;n.drawImage(r,(S-L)/2,(N-Z)/2,L,Z),x={asset:f.asset,source:v}}if(a){n.strokeStyle="rgb(255 255 255 / 0.55)",n.setLineDash([6,6]),n.lineWidth=1;for(let $ of[.05,.1])n.strokeRect(S*$,N*$,S*(1-2*$),N*(1-2*$));n.setLineDash([])}}let K=()=>{E(),n.fillStyle="#000",n.fillRect(0,0,e.width,e.height),x=null},A=0,g=Promise.resolve();function M(r){let f=h.indexOf(tt(h,r));if(f<0)return Promise.resolve(K());let v=h[f],S=Q(v,r),N=P(f),$=T(v,S),L=++A,Z=new Promise(z=>{let J=()=>{A===L&&_(N,v,S),z()};if(N.readyState>=2&&Math.abs(N.currentTime-$)<1e-4)return J();N.addEventListener("seeked",J,{once:!0}),N.currentTime=$});if(g=Z,h[f+1]){let z=P(f+1);z!==N&&(z.currentTime=T(h[f+1],h[f+1].in))}return Z}function D(){for(let r of m.values())r.pause(),r.muted=!0}function B(r,f=!0){y=Math.min(Math.max(0,r),Math.max(0,u-Y(c))),f&&i(y)}function O(r){let f=h.indexOf(tt(h,y));if(f<0)return R(0);let v=(S,N)=>{let $=h[S],L=P(S);L.currentTime=T($,Q($,N)),L.playbackRate=w,L.muted=!1;let{n:Z,d:z}=typeof $.speed=="object"?$.speed:{n:1,d:1},J=(bt,ut)=>{if(r!==b)return;let st=$.at+Math.round((Math.round(ut.mediaTime*7056e5)-$.in)*z/Z);if(st>=$.end-Y(c)/2||L.ended)return L.pause(),L.muted=!0,h[S+1]?(f=S+1,B(h[f].at),v(f,h[f].at)):R(0);_(L,$,Q($,st)),B(st),L.requestVideoFrameCallback(J)};L.requestVideoFrameCallback(J),L.play().catch(()=>r===b&&R(0))};v(f,y)}function q(r){let f=performance.now(),v=async S=>{if(r===b){if(B(y-(S-f)/1e3*7056e5*Math.abs(w)),f=S,await M(y),y===0)return R(0);requestAnimationFrame(v)}};requestAnimationFrame(v)}function R(r){if(r===w&&r!==0)return;w=r;let f=++b;D(),l(w),w>0?O(f):w<0?q(f):(B(lt(y,c)),M(y))}return{load(r,{fps:f,duration:v,shape:S}){return h=r,c=f,u=v,S&&(W=S),++b,D(),w=0,l(0),B(Math.min(y,Math.max(0,u-Y(c)))),M(y)},seek(r){return w!==0&&R(0),B(lt(r,c)),M(y)},setRate:R,get time(){return y},get rate(){return w},get shown(){return x},get settled(){return g},setShape(r){return W=r,M(y)},setZoom(r){return C=r,M(y)},setGuides(r){return a=r,M(y)},pixels:()=>e.width?n.getImageData(0,0,e.width,e.height):null}}var Rt=[{key:"picture",label:"Picture",colour:"--clip-picture"},{key:"overlays",label:"B-roll",colour:"--clip-broll"},{key:"audio",label:"Audio",colour:"--clip-audio"},{key:"captions",label:"Captions",colour:"--clip-caption"}],X=44,Lt=6;function mt({root:e,compact:o=!1,onSeek:d,onSelect:i=()=>{}}){let l=o?Rt.slice(0,1):Rt,n=t("canvas",{class:"lanes","aria-hidden":"true"}),m=o?null:t("div",{class:"lane-labels","aria-hidden":"true"},l.map(g=>t("div",{class:"lane-label"},g.label))),h=t("ul",{class:"clip-list","aria-label":o?"Story":"Clips on the timeline"});e.append(...[m,t("div",{class:"lanes-wrap"},n),h].filter(Boolean));let c=n.getContext("2d"),u={picture:[],overlays:[],audio:[],captions:[]},y=0,w={n:30,d:1},W=0,C=[],a=[],b=new Map,x=null,P=null,T=g=>getComputedStyle(e).getPropertyValue(g).trim()||"#888";function E(){let g=Math.max(1,n.clientWidth),M=l.length*(X+Lt),D=window.devicePixelRatio||1;(n.width!==Math.round(g*D)||n.height!==Math.round(M*D))&&(n.width=Math.round(g*D),n.height=Math.round(M*D),n.style.height=`${M}px`),c.setTransform(D,0,0,D,0,0),c.clearRect(0,0,g,M);let B=O=>y?O/y*g:0;l.forEach((O,q)=>{let R=q*(X+Lt);c.fillStyle=T("--lane"),c.fillRect(0,R,g,X);for(let r of u[O.key]??[]){let f=B(r.at),v=Math.max(2,B(r.end)-f);c.fillStyle=T(O.colour),c.fillRect(f,R+2,v-1,X-4),r.clip&&r.clip===x&&(c.strokeStyle=T("--focus"),c.lineWidth=2,c.strokeRect(f+1,R+3,v-3,X-6));let S=O.key==="audio"||o&&O.key==="picture"?b.get(r.asset):null;if(S&&r.in!==void 0){c.fillStyle=T("--wave");let N=r.out-r.in;for(let $=0;$<v;$++){let L=(r.in+N*$/v)/7056e5,z=(S.peaks[Math.floor(L*S.perSecond)]??0)*(X-8);c.fillRect(f+$,R+X/2-z/2,1,Math.max(1,z))}}}if(O.key==="picture"&&P){c.strokeStyle=T("--ghost"),c.setLineDash([5,4]),c.lineWidth=2;let r=Math.max(y,P.duration)||1;for(let f of P.picture)c.strokeRect(f.at/r*g+1,R+6,Math.max(2,(f.end-f.at)/r*g-2),X-12);c.setLineDash([])}if(O.key==="picture"){c.fillStyle=T("--shot");for(let r of C)c.fillRect(B(r.at)-.5,R,1,8)}}),c.fillStyle=T("--playhead");for(let O of a)c.fillRect(B(O.at)-1,0,3,8);c.fillStyle=T("--playhead"),c.fillRect(B(W)-1,0,2,M)}let _=!1,K=g=>{let M=n.getBoundingClientRect();d(Math.round(Math.min(1,Math.max(0,(g.clientX-M.left)/M.width))*y))};n.addEventListener("pointerdown",g=>{_=!0,n.setPointerCapture(g.pointerId),K(g)}),n.addEventListener("pointermove",g=>_&&K(g)),n.addEventListener("pointerup",()=>_=!1),new ResizeObserver(E).observe(n);function A(g){x=g;for(let M of h.querySelectorAll("button"))M.setAttribute("aria-pressed",String(M.dataset.clip===g));i(g),E()}return{load(g,{duration:M,fps:D,marks:B=[],pins:O=[]}){a=O,u=g,y=M,w=D,C=B,x&&!u.picture.some(q=>q.clip===x)&&(x=null),U(h);for(let q of u.picture.filter((R,r,f)=>f.findIndex(v=>v.clip===R.clip)===r)){let R=t("button",{type:"button","aria-pressed":String(q.clip===x),dataset:{clip:q.clip},onclick:()=>(A(q.clip),d(q.at))},`Clip ${q.clip}, ${et(q.at,w)} to ${et(q.end,w)}`);h.append(t("li",{},R))}E()},setPeaks(g,M){b.set(g,M),E()},setGhost(g){P=g,E()},setTime(g){W=g,E()},select:A,get selected(){return x},draw:E}}var It=new Set(["filler","stutter","restart"]);function Ft({root:e,onSeek:o,onCut:d}){let i=[],l=new Map,n=null,m=[],h=null,c=()=>{for(let u of e.querySelectorAll(".word[aria-pressed='true']"))u.setAttribute("aria-pressed","false");for(let u of m)e.querySelector(`[data-word="${CSS.escape(u)}"]`)?.setAttribute("aria-pressed","true")};return e.addEventListener("click",u=>{let y=u.target.closest(".word");if(!y)return;let w=l.get(y.dataset.word);if(u.shiftKey&&n){let[W,C]=[i.indexOf(n),i.indexOf(w)].sort((a,b)=>a-b);m=i.slice(W,C+1).filter(a=>a.asset===w.asset).map(a=>a.id)}else n=w,m=[w.id],o(w);c()}),e.addEventListener("keydown",u=>{(u.key==="Backspace"||u.key==="Delete")&&m.length&&(u.preventDefault(),u.stopPropagation(),d(l.get(m[0]),l.get(m.at(-1))))}),{load({words:u=[],sentences:y=[],takes:w=[]}){i=u,l=new Map(u.map(a=>[a.id,a])),m=m.filter(a=>l.has(a));let W=new Map(w.map(a=>[a.sentence,a]));if(U(e),!u.length){e.append(t("p",{class:"note"},"No transcript yet. Index a clip in the bin to read its words."));return}let C=y.length?y:[...new Set(u.map(a=>a.asset))].map(a=>{let b=u.filter(x=>x.asset===a);return{id:null,asset:a,firstWord:b[0].id,lastWord:b.at(-1).id,score:1}});for(let a of C){let b=W.get(a.id),x=b&&b.rank>1||a.score===0,P=Number(a.firstWord.split(":w")[1]),T=Number(a.lastWord.split(":w")[1]),E=t("p",{class:`sentence${x?" lost":""}`,dataset:a.id?{sentence:a.id}:{}});b&&E.append(t("span",{class:"tag"},b.rank===1?"best take":`take ${b.rank}`));for(let _=P;_<=T;_++){let K=l.get(`${a.asset}:w${_}`);if(!K)continue;let A=x||K.flags.some(D=>It.has(D)),g=A?`${K.text} (${x?"retake":K.flags.filter(D=>It.has(D)).join(", ")})`:null,M=t("button",{type:"button",class:`word${A?" struck":""}${K.flags.includes("low_confidence")?" unsure":""}`,"aria-pressed":"false","aria-label":g,dataset:{word:K.id}});M.textContent=K.text,E.append(M," ")}e.append(E)}c()},playing(u){u!==h&&(e.querySelector(".word.now")?.classList.remove("now"),h=u,u&&e.querySelector(`[data-word="${CSS.escape(u)}"]`)?.classList.add("now"))},words:()=>i,selection:()=>m.length?[m[0],m.at(-1)]:null,clear(){m=[],n=null,c()}}}var yt=document.getElementById("app"),Wt=["direct","edit","finish"],gt=(e,o)=>{try{if(o===void 0)return localStorage.getItem(e);localStorage.setItem(e,o)}catch{return null}},Ut=()=>{try{return sessionStorage.getItem("kriya-edit-back")}catch{return null}};function Kt(...e){let o=Ut();return t("header",{class:"bar"},o?t("a",{class:"btn ghost",href:o},"\u2190 Kriya Harness"):t("span",{class:"brand"},"Kriya"),t("span",{class:"title"},"Editing Studio"),...e)}function dt(e){U(yt).append(t("main",{class:"center"},t("h1",{},"Open the Studio from Kriya"),t("p",{},e??"Click Editing Studio in Kriya Harness, or run kriya edit and open its link.")))}async function zt(){let e;try{({projects:e}=await F("GET","/projects"))}catch(h){return h.status===401?dt():dt(h.message)}let o=t("input",{id:"new-name",class:"field",required:!0,placeholder:"Pricing reel",autocomplete:"off"}),d=t("input",{id:"new-folder",class:"field",required:!0,placeholder:"/Users/you/Movies/pricing"}),i=t("p",{class:"note",role:"status"}),l=t("form",{class:"panel new",onsubmit:async h=>{h.preventDefault();try{let{id:c}=await F("POST","/projects",{name:o.value.trim(),folder:d.value.trim()});location.hash=`#/p/${c}`}catch(c){i.textContent=c.message}}},t("h2",{},"New project"),t("label",{for:"new-name"},"Name"),o,t("label",{for:"new-folder"},"Folder for the project file (its footage stays where it is)"),d,t("button",{class:"btn primary",type:"submit"},"Create"),i),n=t("section",{class:"panel taste","aria-label":"Your taste"}),m=async h=>{let{proposed:c,confirmed:u}=h??await F("GET","/taste"),y=(w,W)=>async()=>m(await F("POST",`/taste/${encodeURIComponent(w)}/${W}`));U(n).append(t("h2",{},"Your taste"),...c.length||u.length?[]:[t("p",{class:"note"},"Nothing yet. When you make the same choice across projects, Kriya asks here before using it.")],...c.map(w=>t("div",{class:"taste-row"},t("p",{},w.sentence),t("button",{type:"button",class:"btn primary",onclick:y(w.key,"confirm")},"Use it"),t("button",{type:"button",class:"btn",onclick:y(w.key,"dismiss")},"No"))),...u.map(w=>t("div",{class:"taste-row"},t("p",{},w.shown),t("button",{type:"button",class:"btn","aria-label":`Remove the rule ${w.shown}`,onclick:y(w.key,"remove")},"Remove"))))};m().catch(()=>{}),U(yt).append(Kt(),t("main",{class:"home"},t("h1",{},"What are we making?"),t("section",{class:"panel"},t("h2",{},"Projects"),e.length?t("ul",{class:"projects"},e.map(h=>t("li",{},t("a",{class:"btn",href:`#/p/${h.id}`},h.name)))):t("p",{class:"note"},"No projects yet.")),l,n))}async function Zt(e){let o;try{o=await F("GET",`/projects/${e}`)}catch(s){return s.status===401?dt():dt(s.message)}let d=o.project,i=o.assets,l={assets:[],words:[],sentences:[],takes:[],shots:[]},n=[],m={picture:[],overlays:[],audio:[],captions:[]},h=null,c=Wt.includes(gt("kriya-edit-mode"))?gt("kriya-edit-mode"):"direct",u=()=>d.canvas.fps,y=t("span",{class:"time label-mono","aria-live":"off"},"00:00.00"),w=t("span",{class:"chip"},"Preview"),W=t("canvas",{class:"monitor",role:"img","aria-label":"Program monitor"}),C=t("p",{class:"note",role:"status","aria-live":"polite"}),a=Ot({canvas:W,urlOf:s=>`/media/${i.find(p=>p.id===s).media}`,assetOf:s=>i.find(p=>p.id===s),onTime:s=>{y.textContent=`${et(s,u())} / ${et(x(),u())}`,A.setTime(s),g.setTime(s);let p=tt(b(),s),k=p?Q(p,s):null,j=k===null?null:l.words.find(I=>I.asset===p.asset&&k>=I.start&&k<I.end);K.playing(j?.id??null)},onRate:s=>{ot.textContent=s===0?"Play":"Pause",ot.setAttribute("aria-label",s===0?"Play (Space)":`Pause (Space), playing at ${s}\xD7`)}}),b=()=>h?ft(i.find(s=>s.id===h)):n,x=()=>ct(b()),P=t("div",{class:"transcript",tabindex:"-1"}),T=t("div",{class:"strip"}),E=t("div",{class:"timeline"}),_=t("div",{class:"finish"}),K=Ft({root:P,onSeek:s=>{let p=it(n,s.asset,s.start);p!==null?(D(),a.seek(p)):B(s.asset,s.start)},onCut:(s,p)=>q([{op:"remove_range",asset:s.asset,from:{word:s.id,edge:"start"},to:{word:p.id,edge:"end"}}])}),A=mt({root:E,onSeek:s=>(D(),a.seek(s))}),g=mt({root:T,compact:!0,onSeek:s=>(D(),a.seek(s))}),M=$t({root:_,pixels:()=>a.pixels(),project:()=>d});function D(){h&&(h=null,w.textContent="Preview",a.load(n,{fps:u(),duration:ct(n),shape:d.canvas}))}function B(s,p){h=s;let k=i.find(j=>j.id===s).facts;w.textContent="Source",a.load(ft(i.find(j=>j.id===s)),{fps:k.fps??u(),duration:k.duration,shape:{width:k.width??1920,height:k.height??1080}}).then(()=>a.seek(p))}async function O(){let[s,p,k]=await Promise.all([F("GET",`/projects/${e}`),F("GET",`/projects/${e}/plan`),F("GET",`/projects/${e}/index`)]);d=s.project,i=s.assets,l=k,m=p.timeline,n=jt(p.timeline);let j=ct(n),I=Pt(n,l.shots),nt=new Map((l.words??[]).map(G=>[G.id,G])),_t=(d.sequences.find(G=>G.id===d.active)?.markers??[]).flatMap(G=>{let V=G.name.startsWith("Note: ")&&G.at?.word?nt.get(G.at.word):null,H=V?it(n,V.asset,V.start):null;return H==null?[]:[{at:H,name:G.name}]});A.load(m,{duration:j,fps:u(),marks:I,pins:_t}),g.load({picture:m.picture},{duration:j,fps:u(),marks:I}),K.load(l),f(),h||await a.load(n,{fps:u(),duration:j,shape:d.canvas});for(let G of new Set([...m.audio,...m.picture].map(V=>V.asset))){let V=i.find(H=>H.id===G)?.media;V&&i.find(H=>H.id===G).facts.hasAudio&&fetch(`/tiles/${V}?kind=peaks`).then(H=>H.ok?H.json():null).then(H=>H&&(A.setPeaks(G,H.levels[0]),g.setPeaks(G,H.levels[0]))).catch(()=>{})}}async function q(s){try{let p=await F("PATCH",`/projects/${e}`,{ops:s});C.textContent=p.diagnostics?.length?p.diagnostics[0].message:""}catch(p){C.textContent=p.value?.diagnostics?.[0]?.message??p.message}await O()}let R=t("ul",{class:"bin","aria-label":"Footage"}),r=t("input",{id:"add-path",class:"field",placeholder:"/path/to/take.mov",autocomplete:"off"});function f(){U(R);for(let s of i){let p=l.assets.find(I=>I.asset===s.id),k=p?.layers.find(I=>I.layer==="L2"),j=p?k?.status==="ok"?"Indexed":k?.notice??"Indexed, no words":"Not indexed";R.append(t("li",{class:"asset"},t("button",{type:"button",class:"btn",onclick:()=>B(s.id,0)},`${s.path.split(/[\\/]/).at(-1)} \xB7 ${s.kind}`),t("span",{class:"note"},j),t("button",{type:"button",class:"btn",onclick:async()=>(await F("POST",`/projects/${e}/index`,{asset:s.id}),C.textContent="Reading your footage. You can start working now.")},"Index"),t("button",{type:"button",class:"btn",onclick:()=>q([{op:"keep_range",asset:s.id,from:0,to:s.facts.duration}])},"Add to cut")))}}let v=t("section",{class:"panel bin-panel","aria-label":"Bin"},t("h2",{},"Bin"),R,t("form",{class:"row",onsubmit:async s=>{s.preventDefault();try{await F("POST",`/projects/${e}/assets`,{path:r.value.trim()}),r.value="",await O()}catch(p){C.textContent=p.message}}},t("label",{for:"add-path",class:"sr-only"},"Add a file by its path"),r,t("button",{class:"btn",type:"submit"},"Add"))),S=t("input",{id:"prompt",class:"field",placeholder:"Ask for a change",autocomplete:"off"}),N=t("span",{class:"chip selection",hidden:!0}),$=t("div",{class:"proposal","aria-live":"polite"}),L=t("ul",{class:"did","aria-label":"What I did"}),Z=()=>{let s=K.selection();return s?{selection:{words:s},label:`Selected: ${l.words.find(p=>p.id===s[0])?.text??""}${s[0]===s[1]?"":" \u2026"}`}:A.selected?{selection:{clip:A.selected},label:`Selected: clip ${A.selected}`}:{selection:{at:a.time},label:null}},z=()=>{let{label:s}=Z();N.hidden=!s,N.textContent=s??""};P.addEventListener("click",()=>setTimeout(z));function J(s){if(U($),A.setGhost(s?s.timeline:null),g.setGhost(s?s.timeline:null),!s)return;let p=async(k,j)=>{try{let I=await F("POST",`/projects/${e}/proposals/${s.id}`,{accept:k,...j?{only:j}:{}});if(C.textContent=I.dropped.length?`Not applied, because you changed that part: ${I.dropped.map(nt=>nt.change).join("; ")}.`:k?"Done. Undo with Cmd+Z.":"Left as it was.",k)for(let nt of j?j.map(Mt=>s.changes[Mt]):s.changes)L.prepend(t("li",{},nt))}catch(I){C.textContent=I.message}J(null),await O()};$.append(t("p",{class:"lead"},"Proposed, not applied yet"),t("ul",{},s.changes.map((k,j)=>t("li",{},t("span",{},k),s.changes.length>1?t("button",{type:"button",class:"btn",onclick:()=>p(!0,[j])},"Only this"):null))),t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>p(!0)},s.changes.length>1?"Accept all":"Accept"),t("button",{type:"button",class:"btn",onclick:()=>p(!1)},"Reject")))}let bt=t("form",{class:"prompt",onsubmit:async s=>{s.preventDefault();let p=S.value.trim();if(p){C.textContent="Thinking about that\u2026";try{let{proposal:k,reason:j}=await F("POST",`/projects/${e}/ask`,{text:p,selection:Z().selection});C.textContent=k?"":j??"Kriya couldn't turn that into an edit.",k&&(S.value=""),J(k)}catch(k){C.textContent=k.status===0||k.status>=500?"I can't reach Kriya, so I can't make changes by asking. You can still edit by hand.":k.message}}}},t("label",{for:"prompt",class:"sr-only"},"Ask for a change"),S,t("button",{class:"btn primary",type:"submit"},"Ask")),ut={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you",not_checked:"Not checked"},st=t("button",{type:"button",class:"btn",onclick:async()=>{try{at=(await F("POST",`/projects/${e}/make`,{})).id,C.textContent="Reading your footage. You can start working now."}catch(s){C.textContent=s.message}}},"Make a reel"),at=null;async function Dt(){if(!at)return;let s=(await F("GET","/jobs")).jobs.find(k=>k.id===at);if(!s||!["done","failed","canceled"].includes(s.status))return;if(at=null,s.status!=="done")return C.textContent=s.error??"The reel stopped.";let p=JSON.parse(s.output);C.textContent=`${ut[p.verdict]??p.verdict}. ${p.notes.join(" ")}`;for(let k of[...p.changes].reverse())L.prepend(t("li",{},k))}let ot=t("button",{type:"button",class:"btn primary",onclick:()=>pt({type:"toggle"})},"Play"),qt={project:()=>d.canvas,"16:9":()=>({width:1920,height:1080}),"9:16":()=>({width:1080,height:1920})},wt=t("select",{class:"field small","aria-label":"Preview shape",onchange:()=>a.setShape(qt[wt.value]())},["project","16:9","9:16"].map(s=>t("option",{value:s},s==="project"?"Project shape":s))),kt=t("input",{type:"range",min:"1",max:"3",step:"0.05",value:"1",class:"zoom","aria-label":"Zoom",oninput:()=>a.setZoom(Number(kt.value))}),xt=t("input",{type:"checkbox",id:"guides",onchange:()=>a.setGuides(xt.checked)});function pt(s){if(!s)return;if(s.type==="mode")return rt(s.mode);if(s.type==="prompt")return S.focus();if(s.type==="undo")return F("PATCH",`/projects/${e}`,{undo:!0}).then(O);if(s.type==="redo")return C.textContent="Redo isn't here yet.";if(s.type==="split"){let I=tt(n,a.time);return I&&q([{op:"split",clip:I.clip,at:Q(I,a.time)}])}if(s.type==="delete")return A.selected&&q([{op:"ripple_delete",clip:A.selected}]);let p={fps:h?i.find(I=>I.id===h).facts.fps??u():u(),duration:x()},k={t:a.time,rate:a.rate},j=At(k,s,p);j.rate!==k.rate&&a.setRate(j.rate),(j.t!==k.t||s.type==="seek")&&a.seek(j.t)}function rt(s){c=s,gt("kriya-edit-mode",c),St.dataset.mode=c;for(let p of vt.querySelectorAll("button"))p.setAttribute("aria-pressed",String(p.dataset.mode===c));A.draw(),g.draw(),c==="finish"&&M.refresh().catch(()=>{})}let vt=t("div",{class:"modes",role:"group","aria-label":"Mode"},Wt.map((s,p)=>t("button",{type:"button",class:"btn",dataset:{mode:s},"aria-pressed":"false","aria-keyshortcuts":String(p+1),onclick:()=>rt(s)},s[0].toUpperCase()+s.slice(1)))),St=t("div",{class:"workspace"},Kt(t("span",{class:"project-name"},d.name),vt),t("div",{class:"grid"},t("div",{class:"area-bin"},v),t("section",{class:"area-monitor panel","aria-label":"Monitor"},t("div",{class:"monitor-frame"},W),t("div",{class:"transport"},ot,y,w,wt,t("label",{class:"inline"},xt," Safe zones"),t("label",{class:"inline"},"Zoom ",kt))),t("aside",{class:"area-kriya panel","aria-label":"Kriya"},t("h2",{},"Kriya"),st,N,bt,C,$,t("h2",{},"What I did"),L),t("section",{class:"area-transcript panel","aria-label":"Transcript"},t("h2",{},"Transcript"),P),t("div",{class:"area-strip"},T),t("section",{class:"area-timeline panel","aria-label":"Timeline"},E),t("div",{class:"area-finish"},_)));U(yt).append(St),rt(c),window.onkeydown=s=>{let p=s.target.closest?.("input, select, textarea");if(p&&s.key!=="Escape")return;if(s.key==="Escape")return p?document.activeElement?.blur():(K.clear(),A.select(null),z());let k=Et(s.key,{shift:s.shiftKey,mod:s.metaKey||s.ctrlKey});k&&(k.type==="toggle"&&s.target.closest?.("button")&&s.target!==ot||(s.preventDefault(),pt(k)))},setInterval(()=>c==="finish"&&M.scopes(),250),new EventSource("/events").addEventListener("job",()=>{c==="finish"&&M.refresh().catch(()=>{}),Dt().catch(()=>{}),O().catch(()=>{})}),await O(),window.__studio={monitor:a,act:pt,reload:O,setMode:rt,get pieces(){return n}}}function Nt(){let e=/^#\/p\/([0-9a-f]{16})$/.exec(location.hash);e?Zt(e[1]):zt()}window.addEventListener("hashchange",Nt);Nt();
1
+ function e(s,o={},...h){let u=document.createElement(s);for(let[p,a]of Object.entries(o??{}))a==null||a===!1||(p.startsWith("on")?u.addEventListener(p.slice(2),a):p==="class"?u.className=a:p==="dataset"?Object.assign(u.dataset,a):a===!0?u.setAttribute(p,""):u.setAttribute(p,String(a)));for(let p of h.flat())p!=null&&p!==!1&&u.append(p instanceof Node?p:String(p));return u}var q=s=>(s.replaceChildren(),s);async function O(s,o,h){let u=await fetch(o,{method:s,headers:h===void 0?{}:{"content-type":"application/json"},body:h===void 0?void 0:JSON.stringify(h),credentials:"same-origin"}),p=await u.json().catch(()=>({}));if(!u.ok){let a=new Error(p.message??`The Edit Host answered ${u.status}.`);throw a.status=u.status,a.value=p,a}return p}var bt=(s,o,h)=>.2126*s+.7152*o+.0722*h;function wt(s,o=128){let h=new Uint32Array(256),u=Array.from({length:o},()=>new Uint32Array(64)),{data:p,width:a,height:v}=s,m=Math.max(1,Math.floor(a*v/6e4));for(let d=0,S=0;S<a*v;S+=m,d=S*4){let x=Math.min(255,Math.round(bt(p[d],p[d+1],p[d+2])));h[x]++,u[Math.min(o-1,Math.floor(S%a/a*o))][x>>2]++}return{histogram:h,waveform:u}}function Ze({root:s,pixels:o,project:h}){let u=e("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma histogram"}),p=e("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma waveform"}),a=e("ul",{class:"jobs","aria-live":"polite"}),v=e("p",{class:"note",role:"status"}),m=async g=>{v.textContent="";try{await O("POST","/jobs",{project:h().id,quality:g}),w()}catch(k){v.textContent=k.message}},d=e("p",{class:"note",role:"status"}),S=e("ul",{class:"jobs","aria-label":"Handoff files"}),x=async()=>{d.textContent="",q(S);try{let g=await O("POST",`/projects/${h().id}/export/handoff`),k=g.chapters.length,c=k?`, ${k} chapter${k===1?"":"s"}`:"";d.textContent=`Written to ${g.folder}, with ${g.media} media file${g.media===1?"":"s"} linked${c}.`;for(let $ of g.files)S.append(e("li",{},e("span",{class:"file"},$)));for(let $ of g.omitted)S.append(e("li",{},e("span",{class:"label-mono"},$.format),` ${$.reason}`))}catch(g){d.textContent=g.message}};s.append(e("section",{class:"panel scopes","aria-label":"Scopes"},e("h2",{},"Scopes"),e("div",{class:"scope-row"},e("figure",{},u,e("figcaption",{},"Histogram")),e("figure",{},p,e("figcaption",{},"Waveform"))),e("p",{class:"note"},"Measured on the preview: 8-bit, from the proxy.")),e("section",{class:"panel export","aria-label":"Export"},e("h2",{},"Export"),e("div",{class:"row"},e("button",{type:"button",class:"btn",onclick:()=>m("draft")},"Render a draft"),e("button",{type:"button",class:"btn primary",onclick:()=>m("master")},"Render the master")),e("p",{class:"note"},"Files go to the exports folder beside the project. Sources are never written."),v,a),e("section",{class:"panel handoff","aria-label":"Handoff"},e("h2",{},"Handoff"),e("p",{class:"note"},"For Premiere, Resolve or Final Cut: the cut as OTIO, FCPXML, EDL and SRT, with chapters, and the media linked beside them."),e("div",{class:"row"},e("button",{type:"button",class:"btn",onclick:x},"Export for another editor")),d,S));function i(g,k){let c=g.getContext("2d");c.clearRect(0,0,g.width,g.height),c.fillStyle=getComputedStyle(s).getPropertyValue("--scope").trim()||"#6cc0b8",k(c)}function C(){let g=o();if(!g)return;let{histogram:k,waveform:c}=wt(g),$=Math.max(1,...k);i(u,T=>k.forEach((D,H)=>T.fillRect(H,100-D/$*100,1,D/$*100))),i(p,T=>c.forEach((D,H)=>D.forEach((U,_)=>{U&&(T.globalAlpha=Math.min(1,.15+U/200),T.fillRect(H*2,100-_/64*100-2,2,2))})))}async function w(){let{jobs:g}=await O("GET","/jobs");q(a);for(let k of g.filter(c=>c.project===h().id&&c.kind==="render").reverse().slice(0,8)){let c=k.output?k.output.split(/[\\/]/).at(-1):null;a.append(e("li",{},e("span",{class:"label-mono"},k.status),` ${k.progress}%`,c?e("span",{class:"file"},` ${c}`):null,k.error?e("span",{class:"error"},` ${k.error}`):null))}}return{scopes:C,refresh:w}}var Ve=s=>typeof s=="number"?{n:s,d:1}:s??{n:1,d:1},Xe=s=>[...s?.picture??[]].sort((o,h)=>o.at-h.at),Oe=s=>[{clip:null,asset:s.id,in:0,out:s.facts.duration,at:0,end:s.facts.duration,speed:{n:1,d:1}}],ce=(s,o)=>s.find(h=>o>=h.at&&o<h.end)??(s.length&&o>=s.at(-1).end?s.at(-1):null);function oe(s,o){if(s.hold)return s.in;let{n:h,d:u}=Ve(s.speed);return Math.min(s.out,s.in+Math.round((o-s.at)*h/u))}function we(s,o,h){for(let u of s){if(u.asset!==o||u.hold||h<u.in||h>=u.out)continue;let{n:p,d:a}=Ve(u.speed);return u.at+Math.round((h-u.in)*a/p)}return null}var ke=s=>s.length?Math.max(...s.map(o=>o.end)):0;function Qe(s,o){let h=[];for(let u of o){let p=we(s,u.asset,u.start);p!==null&&p>0&&h.push({id:u.id,at:p})}return h}var te=s=>7056e5*s.d/s.n,et=(s,o)=>Math.floor(s/te(o)+1e-9),xe=(s,o)=>Math.round(et(s,o)*te(o));function le(s,o){let h=Math.max(0,s)/7056e5,u=Math.floor(h/60),p=Math.floor(h%60),a=et(Math.max(0,s)-Math.floor(h)*7056e5,o);return`${String(u).padStart(2,"0")}:${String(p).padStart(2,"0")}.${String(a).padStart(2,"0")}`}function tt(s,{shift:o=!1,mod:h=!1}={}){if(h)return s==="z"||s==="Z"?{type:o?"redo":"undo"}:null;switch(s){case" ":return{type:"toggle"};case"k":case"K":return{type:"rate",rate:0};case"l":case"L":return{type:"faster"};case"j":case"J":return{type:"reverse"};case"ArrowRight":return{type:"step",frames:o?null:1,seconds:o?1:null};case"ArrowLeft":return{type:"step",frames:o?null:-1,seconds:o?-1:null};case"Home":return{type:"seek",t:0};case"1":return{type:"mode",mode:"direct"};case"2":return{type:"mode",mode:"edit"};case"3":return{type:"mode",mode:"finish"};case"/":return{type:"prompt"};case"s":case"S":return{type:"split"};case"Backspace":case"Delete":return{type:"delete"};default:return null}}function st(s,o,{fps:h,duration:u}){let p=Math.max(0,u-te(h)),a=v=>Math.min(Math.max(0,Math.round(v)),p);switch(o.type){case"toggle":return{...s,rate:s.rate===0?1:0};case"rate":return{...s,rate:o.rate};case"faster":return{...s,rate:s.rate<=0?1:2};case"reverse":return{...s,rate:s.rate>=0?-1:-2};case"step":{let v=o.frames!==null?o.frames*te(h):o.seconds*7056e5;return{rate:0,t:a(xe(s.t,h)+v)}}case"seek":return{...s,t:a(o.t)};case"tick":{let v=a(o.t);return{t:v,rate:v===0&&s.rate<0||v===p&&s.rate>0?0:s.rate}}default:return s}}var kt=1280;function nt({canvas:s,urlOf:o,assetOf:h,onTime:u,onRate:p}){let a=s.getContext("2d",{willReadFrequently:!0}),v=new Map,m=[],d={n:30,d:1},S=0,x=0,i=0,C={width:1920,height:1080},w=1,g=!1,k=0,c=null;function $(l){let y=m[l],j=`${y.asset}:${l%2}`;if(!v.has(j)){let E=document.createElement("video");Object.assign(E,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:o(y.asset)}),v.set(j,E)}return v.get(j)}function T(l,y){let j=h(l.asset)?.facts?.fps??d;return(y+te(j)/2)/7056e5}function D(){let l=Math.min(1,kt/Math.max(C.width,C.height)),y=Math.round(C.width*l),j=Math.round(C.height*l);(s.width!==y||s.height!==j)&&Object.assign(s,{width:y,height:j})}function H(l,y,j){D();let{width:E,height:W}=s;if(a.fillStyle="#000",a.fillRect(0,0,E,W),l?.videoWidth){let R=Math.max(E/l.videoWidth,W/l.videoHeight)*w,K=l.videoWidth*R,X=l.videoHeight*R;a.drawImage(l,(E-K)/2,(W-X)/2,K,X),c={asset:y.asset,source:j}}if(g){a.strokeStyle="rgb(255 255 255 / 0.55)",a.setLineDash([6,6]),a.lineWidth=1;for(let R of[.05,.1])a.strokeRect(E*R,W*R,E*(1-2*R),W*(1-2*R));a.setLineDash([])}}let U=()=>{D(),a.fillStyle="#000",a.fillRect(0,0,s.width,s.height),c=null},_=0,f=Promise.resolve();function M(l){let y=m.indexOf(ce(m,l));if(y<0)return Promise.resolve(U());let j=m[y],E=oe(j,l),W=$(y),R=T(j,E),K=++_,X=new Promise(z=>{let Q=()=>{_===K&&H(W,j,E),z()};if(W.readyState>=2&&Math.abs(W.currentTime-R)<1e-4)return Q();W.addEventListener("seeked",Q,{once:!0}),W.currentTime=R});if(f=X,m[y+1]){let z=$(y+1);z!==W&&(z.currentTime=T(m[y+1],m[y+1].in))}return X}function B(){for(let l of v.values())l.pause(),l.muted=!0}function L(l,y=!0){x=Math.min(Math.max(0,l),Math.max(0,S-te(d))),y&&u(x)}function F(l){let y=m.indexOf(ce(m,x));if(y<0)return I(0);let j=(E,W)=>{let R=m[E],K=$(E);K.currentTime=T(R,oe(R,W)),K.playbackRate=i,K.muted=!1;let{n:X,d:z}=typeof R.speed=="object"?R.speed:{n:1,d:1},Q=(De,ae)=>{if(l!==k)return;let se=R.at+Math.round((Math.round(ae.mediaTime*7056e5)-R.in)*z/X);if(se>=R.end-te(d)/2||K.ended)return K.pause(),K.muted=!0,m[E+1]?(y=E+1,L(m[y].at),j(y,m[y].at)):I(0);H(K,R,oe(R,se)),L(se),K.requestVideoFrameCallback(Q)};K.requestVideoFrameCallback(Q),K.play().catch(()=>l===k&&I(0))};j(y,x)}function A(l){let y=performance.now(),j=async E=>{if(l===k){if(L(x-(E-y)/1e3*7056e5*Math.abs(i)),y=E,await M(x),x===0)return I(0);requestAnimationFrame(j)}};requestAnimationFrame(j)}function I(l){if(l===i&&l!==0)return;i=l;let y=++k;B(),p(i),i>0?F(y):i<0?A(y):(L(xe(x,d)),M(x))}return{load(l,{fps:y,duration:j,shape:E}){return m=l,d=y,S=j,E&&(C=E),++k,B(),i=0,p(0),L(Math.min(x,Math.max(0,S-te(d)))),M(x)},seek(l){return i!==0&&I(0),L(xe(l,d)),M(x)},setRate:I,get time(){return x},get rate(){return i},get shown(){return c},get settled(){return f},setShape(l){return C=l,M(x)},setZoom(l){return w=l,M(x)},setGuides(l){return g=l,M(x)},pixels:()=>s.width?a.getImageData(0,0,s.width,s.height):null}}var at=[{key:"picture",label:"Picture",colour:"--clip-picture"},{key:"overlays",label:"B-roll",colour:"--clip-broll"},{key:"audio",label:"Audio",colour:"--clip-audio"},{key:"captions",label:"Captions",colour:"--clip-caption"}],ne=44,ot=6;function Ie({root:s,compact:o=!1,onSeek:h,onSelect:u=()=>{}}){let p=o?at.slice(0,1):at,a=e("canvas",{class:"lanes","aria-hidden":"true"}),v=o?null:e("div",{class:"lane-labels","aria-hidden":"true"},p.map(f=>e("div",{class:"lane-label"},f.label))),m=e("ul",{class:"clip-list","aria-label":o?"Story":"Clips on the timeline"});s.append(...[v,e("div",{class:"lanes-wrap"},a),m].filter(Boolean));let d=a.getContext("2d"),S={picture:[],overlays:[],audio:[],captions:[]},x=0,i={n:30,d:1},C=0,w=[],g=[],k=new Map,c=null,$=null,T=f=>getComputedStyle(s).getPropertyValue(f).trim()||"#888";function D(){let f=Math.max(1,a.clientWidth),M=p.length*(ne+ot),B=window.devicePixelRatio||1;(a.width!==Math.round(f*B)||a.height!==Math.round(M*B))&&(a.width=Math.round(f*B),a.height=Math.round(M*B),a.style.height=`${M}px`),d.setTransform(B,0,0,B,0,0),d.clearRect(0,0,f,M);let L=F=>x?F/x*f:0;p.forEach((F,A)=>{let I=A*(ne+ot);d.fillStyle=T("--lane"),d.fillRect(0,I,f,ne);for(let l of S[F.key]??[]){let y=L(l.at),j=Math.max(2,L(l.end)-y);d.fillStyle=T(F.colour),d.fillRect(y,I+2,j-1,ne-4),l.clip&&l.clip===c&&(d.strokeStyle=T("--focus"),d.lineWidth=2,d.strokeRect(y+1,I+3,j-3,ne-6));let E=F.key==="audio"||o&&F.key==="picture"?k.get(l.asset):null;if(E&&l.in!==void 0){d.fillStyle=T("--wave");let W=l.out-l.in;for(let R=0;R<j;R++){let K=(l.in+W*R/j)/7056e5,z=(E.peaks[Math.floor(K*E.perSecond)]??0)*(ne-8);d.fillRect(y+R,I+ne/2-z/2,1,Math.max(1,z))}}}if(F.key==="picture"&&$){d.strokeStyle=T("--ghost"),d.setLineDash([5,4]),d.lineWidth=2;let l=Math.max(x,$.duration)||1;for(let y of $.picture)d.strokeRect(y.at/l*f+1,I+6,Math.max(2,(y.end-y.at)/l*f-2),ne-12);d.setLineDash([])}if(F.key==="picture"){d.fillStyle=T("--shot");for(let l of w)d.fillRect(L(l.at)-.5,I,1,8)}}),d.fillStyle=T("--playhead");for(let F of g)d.fillRect(L(F.at)-1,0,3,8);d.fillStyle=T("--playhead"),d.fillRect(L(C)-1,0,2,M)}let H=!1,U=f=>{let M=a.getBoundingClientRect();h(Math.round(Math.min(1,Math.max(0,(f.clientX-M.left)/M.width))*x))};a.addEventListener("pointerdown",f=>{H=!0,a.setPointerCapture(f.pointerId),U(f)}),a.addEventListener("pointermove",f=>H&&U(f)),a.addEventListener("pointerup",()=>H=!1),new ResizeObserver(D).observe(a);function _(f){c=f;for(let M of m.querySelectorAll("button"))M.setAttribute("aria-pressed",String(M.dataset.clip===f));u(f),D()}return{load(f,{duration:M,fps:B,marks:L=[],pins:F=[]}){g=F,S=f,x=M,i=B,w=L,c&&!S.picture.some(A=>A.clip===c)&&(c=null),q(m);for(let A of S.picture.filter((I,l,y)=>y.findIndex(j=>j.clip===I.clip)===l)){let I=e("button",{type:"button","aria-pressed":String(A.clip===c),dataset:{clip:A.clip},onclick:()=>(_(A.clip),h(A.at))},`Clip ${A.clip}, ${le(A.at,i)} to ${le(A.end,i)}`);m.append(e("li",{},I))}D()},setPeaks(f,M){k.set(f,M),D()},setGhost(f){$=f,D()},setTime(f){C=f,D()},select:_,get selected(){return c},draw:D}}var rt=new Set(["filler","stutter","restart"]);function it({root:s,onSeek:o,onCut:h,onFix:u=async()=>{}}){let p=[],a=new Map,v=null,m=[],d=null,S=()=>{for(let i of s.querySelectorAll(".word[aria-pressed='true']"))i.setAttribute("aria-pressed","false");for(let i of m)s.querySelector(`[data-word="${CSS.escape(i)}"]`)?.setAttribute("aria-pressed","true")};s.addEventListener("click",i=>{let C=i.target.closest(".word");if(!C)return;let w=a.get(C.dataset.word);if(i.shiftKey&&v){let[g,k]=[p.indexOf(v),p.indexOf(w)].sort((c,$)=>c-$);m=p.slice(g,k+1).filter(c=>c.asset===w.asset).map(c=>c.id)}else v=w,m=[w.id],o(w);S()});function x(i){let C=a.get(i.dataset.word);if(!C)return;let w=e("input",{class:"word-edit",value:C.text,size:String(Math.max(4,C.text.length+2)),maxlength:"60","aria-label":`Fix the word "${C.text}"`});i.replaceWith(w),w.focus(),w.select();let g=!1,k=async c=>{if(g)return;g=!0;let $=w.value.trim();w.replaceWith(i),c&&$&&$!==C.text?await u(C,$):i.focus()};w.addEventListener("keydown",c=>{c.stopPropagation(),c.key==="Enter"?(c.preventDefault(),k(!0)):c.key==="Escape"&&(c.preventDefault(),k(!1))}),w.addEventListener("blur",()=>k(!0))}return s.addEventListener("dblclick",i=>{let C=i.target.closest(".word");C&&x(C)}),s.addEventListener("keydown",i=>{if(i.key==="F2"&&i.target.closest(".word"))return i.preventDefault(),i.stopPropagation(),x(i.target.closest(".word"));(i.key==="Backspace"||i.key==="Delete")&&m.length&&(i.preventDefault(),i.stopPropagation(),h(a.get(m[0]),a.get(m.at(-1))))}),{load({words:i=[],sentences:C=[],takes:w=[]}){p=i,a=new Map(i.map(c=>[c.id,c])),m=m.filter(c=>a.has(c));let g=new Map(w.map(c=>[c.sentence,c]));if(q(s),!i.length){s.append(e("p",{class:"note"},"No transcript yet. Index a clip in the bin to read its words."));return}let k=C.length?C:[...new Set(i.map(c=>c.asset))].map(c=>{let $=i.filter(T=>T.asset===c);return{id:null,asset:c,firstWord:$[0].id,lastWord:$.at(-1).id,score:1}});for(let c of k){let $=g.get(c.id),T=$&&$.rank>1||c.score===0,D=Number(c.firstWord.split(":w")[1]),H=Number(c.lastWord.split(":w")[1]),U=e("p",{class:`sentence${T?" lost":""}`,dataset:c.id?{sentence:c.id}:{}});$&&U.append(e("span",{class:"tag"},$.rank===1?"best take":`take ${$.rank}`));for(let _=D;_<=H;_++){let f=a.get(`${c.asset}:w${_}`);if(!f)continue;let M=T||f.flags.some(A=>rt.has(A)),B=M?`${f.text} (${T?"retake":f.flags.filter(A=>rt.has(A)).join(", ")})`:null,L=typeof f.heard=="string",F=e("button",{type:"button",class:`word${M?" struck":""}${!L&&f.flags.includes("low_confidence")?" unsure":""}${L?" fixed":""}`,"aria-pressed":"false","aria-label":B??(L?`${f.text} (fixed; heard as ${f.heard})`:null),title:L?`Heard as "${f.heard}". Double-click to change.`:"Double-click to fix this word",dataset:{word:f.id}});F.textContent=f.text,U.append(F," ")}s.append(U)}S()},playing(i){i!==d&&(s.querySelector(".word.now")?.classList.remove("now"),d=i,i&&s.querySelector(`[data-word="${CSS.escape(i)}"]`)?.classList.add("now"))},words:()=>p,selection:()=>m.length?[m[0],m.at(-1)]:null,clear(){m=[],v=null,S()}}}var Fe=document.getElementById("app"),ct=["direct","edit","finish"],Ne=(s,o)=>{try{if(o===void 0)return localStorage.getItem(s);localStorage.setItem(s,o)}catch{return null}},xt=()=>{try{return sessionStorage.getItem("kriya-edit-back")}catch{return null}};function lt(...s){let o=xt();return e("header",{class:"bar"},o?e("a",{class:"btn ghost",href:o},"\u2190 Kriya Harness"):e("span",{class:"brand"},"Kriya"),e("span",{class:"title"},"Editing Studio"),...s)}function ve(s){q(Fe).append(e("main",{class:"center"},e("h1",{},"Open the Studio from Kriya"),e("p",{},s??"Click Editing Studio in Kriya Harness, or run kriya edit and open its link.")))}async function vt(){let s;try{({projects:s}=await O("GET","/projects"))}catch(m){return m.status===401?ve():ve(m.message)}let o=e("input",{id:"new-name",class:"field",required:!0,placeholder:"Pricing reel",autocomplete:"off"}),h=e("input",{id:"new-folder",class:"field",required:!0,placeholder:"/Users/you/Movies/pricing"}),u=e("p",{class:"note",role:"status"}),p=e("form",{class:"panel new",onsubmit:async m=>{m.preventDefault();try{let{id:d}=await O("POST","/projects",{name:o.value.trim(),folder:h.value.trim()});location.hash=`#/p/${d}`}catch(d){u.textContent=d.message}}},e("h2",{},"New project"),e("label",{for:"new-name"},"Name"),o,e("label",{for:"new-folder"},"Folder for the project file (its footage stays where it is)"),h,e("button",{class:"btn primary",type:"submit"},"Create"),u),a=e("section",{class:"panel taste","aria-label":"Your taste"}),v=async m=>{let{proposed:d,confirmed:S}=m??await O("GET","/taste"),x=(i,C)=>async()=>v(await O("POST",`/taste/${encodeURIComponent(i)}/${C}`));q(a).append(e("h2",{},"Your taste"),...d.length||S.length?[]:[e("p",{class:"note"},"Nothing yet. When you make the same choice across projects, Kriya asks here before using it.")],...d.map(i=>e("div",{class:"taste-row"},e("p",{},i.sentence),e("button",{type:"button",class:"btn primary",onclick:x(i.key,"confirm")},"Use it"),e("button",{type:"button",class:"btn",onclick:x(i.key,"dismiss")},"No"))),...S.map(i=>e("div",{class:"taste-row"},e("p",{},i.shown),e("button",{type:"button",class:"btn","aria-label":`Remove the rule ${i.shown}`,onclick:x(i.key,"remove")},"Remove"))))};v().catch(()=>{}),q(Fe).append(lt(),e("main",{class:"home"},e("h1",{},"What are we making?"),e("section",{class:"panel"},e("h2",{},"Projects"),s.length?e("ul",{class:"projects"},s.map(m=>e("li",{},e("a",{class:"btn",href:`#/p/${m.id}`},m.name)))):e("p",{class:"note"},"No projects yet.")),p,a))}async function St(s){let o;try{o=await O("GET",`/projects/${s}`)}catch(t){return t.status===401?ve():ve(t.message)}let h=o.project,u=o.assets,p={assets:[],words:[],sentences:[],takes:[],shots:[]},a=[],v={picture:[],overlays:[],audio:[],captions:[]},m=null,d=ct.includes(Ne("kriya-edit-mode"))?Ne("kriya-edit-mode"):"direct",S=()=>h.canvas.fps,x=e("span",{class:"time label-mono","aria-live":"off"},"00:00.00"),i=e("span",{class:"chip"},"Preview"),C=e("canvas",{class:"monitor",role:"img","aria-label":"Program monitor"}),w=e("p",{class:"note",role:"status","aria-live":"polite"}),g=nt({canvas:C,urlOf:t=>`/media/${u.find(n=>n.id===t).media}`,assetOf:t=>u.find(n=>n.id===t),onTime:t=>{x.textContent=`${le(t,S())} / ${le($(),S())}`,f.setTime(t),M.setTime(t);let n=ce(c(),t),r=n?oe(n,t):null,b=r===null?null:p.words.find(P=>P.asset===n.asset&&r>=P.start&&r<P.end);_.playing(b?.id??null)},onRate:t=>{ye.textContent=t===0?"Play":"Pause",ye.setAttribute("aria-label",t===0?"Play (Space)":`Pause (Space), playing at ${t}\xD7`)}}),k=()=>({"16:9":{width:1920,height:1080},"9:16":{width:1080,height:1920}})[_e.value]??h.canvas,c=()=>m?Oe(u.find(t=>t.id===m)):a,$=()=>ke(c()),T=e("div",{class:"transcript",tabindex:"-1"}),D=e("div",{class:"strip"}),H=e("div",{class:"timeline"}),U=e("div",{class:"finish"}),_=it({root:T,onSeek:t=>{let n=we(a,t.asset,t.start);n!==null?(L(),g.seek(n)):F(t.asset,t.start)},onCut:(t,n)=>I([{op:"remove_range",asset:t.asset,from:{word:t.id,edge:"start"},to:{word:n.id,edge:"end"}}]),onFix:async(t,n)=>{try{await O("POST",`/projects/${s}/words/${encodeURIComponent(t.id)}`,{text:n}),w.textContent=`Fixed "${t.text}" to "${n}". Captions and Kriya use it from now on.`}catch(r){w.textContent=r.message}await A()}}),f=Ie({root:H,onSeek:t=>(L(),g.seek(t))}),M=Ie({root:D,compact:!0,onSeek:t=>(L(),g.seek(t))}),B=Ze({root:U,pixels:()=>g.pixels(),project:()=>h});function L(){m&&(m=null,i.textContent="Preview",g.load(a,{fps:S(),duration:ke(a),shape:k()}))}function F(t,n){m=t;let r=u.find(b=>b.id===t).facts;i.textContent="Source",g.load(Oe(u.find(b=>b.id===t)),{fps:r.fps??S(),duration:r.duration,shape:{width:r.width??1920,height:r.height??1080}}).then(()=>g.seek(n))}async function A(){let[t,n,r]=await Promise.all([O("GET",`/projects/${s}`),O("GET",`/projects/${s}/plan`),O("GET",`/projects/${s}/index`)]);h=t.project,u=t.assets,p=r,v=n.timeline,a=Xe(n.timeline);let b=ke(a),P=Qe(a,p.shots),Z=new Map((p.words??[]).map(N=>[N.id,N])),J=(h.sequences.find(N=>N.id===h.active)?.markers??[]).flatMap(N=>{let V=N.name.startsWith("Note: ")&&N.at?.word?Z.get(N.at.word):null,Y=V?we(a,V.asset,V.start):null;return Y==null?[]:[{at:Y,name:N.name}]});f.load(v,{duration:b,fps:S(),marks:P,pins:J}),M.load({picture:v.picture},{duration:b,fps:S(),marks:P}),_.load(p),Ee(),W(),m||await g.load(a,{fps:S(),duration:b,shape:k()});for(let N of new Set([...v.audio,...v.picture].map(V=>V.asset))){let V=u.find(Y=>Y.id===N)?.media;V&&u.find(Y=>Y.id===N).facts.hasAudio&&fetch(`/tiles/${V}?kind=peaks`).then(Y=>Y.ok?Y.json():null).then(Y=>Y&&(f.setPeaks(N,Y.levels[0]),M.setPeaks(N,Y.levels[0]))).catch(()=>{})}}async function I(t){try{let n=await O("PATCH",`/projects/${s}`,{ops:t});w.textContent=n.diagnostics?.length?n.diagnostics[0].message:""}catch(n){w.textContent=n.value?.diagnostics?.[0]?.message??n.message}await A()}let l=e("ul",{class:"bin","aria-label":"Footage"}),y=new Map,j=t=>[...y.values()].find(n=>n.kind==="index"&&n.asset===t&&["pending","running"].includes(n.status)),E=(t,n)=>{let r=e("span",{class:t===null?"busy":""});return t!==null&&(r.style.width=`${t}%`),e("div",{class:"progress",role:"progressbar","aria-label":n,"aria-valuemin":"0","aria-valuemax":"100",...t===null?{}:{"aria-valuenow":String(t)}},r)};function W(){q(l);for(let t of u.filter(n=>n.kind!=="reference")){let n=p.assets.find(J=>J.asset===t.id),r=n?.layers.find(J=>J.layer==="L2"),b=j(t.id),P=ee?.speech?"Indexed, no words yet: set up speech-to-text above":r?.notice??"Indexed, no words",Z=b?`Reading this file\u2026 ${b.progress??0}%`:n?r?.status==="ok"?"Indexed":P:"Not indexed",G=["video","audio"].includes(t.kind);l.append(e("li",{class:"asset"},e("button",{type:"button",class:"btn",onclick:()=>F(t.id,0)},`${t.path.split(/[\\/]/).at(-1)} \xB7 ${t.kind}`),e("span",{class:"note"},t.offline?"Offline: the file has moved":Z),b?E(b.progress??0,`Indexing ${t.path.split(/[\\/]/).at(-1)}`):null,G?e("button",{type:"button",class:"btn",disabled:!!b,onclick:()=>R(t)},n?"Index again":"Index"):null,G?e("button",{type:"button",class:"btn",onclick:()=>I([{op:"keep_range",asset:t.id,from:0,to:t.facts.duration}])},"Add to cut"):null))}ut()}async function R(t){ee?.speech&&!ee.setup?.error&&(w.textContent="Your file is indexed without words until speech-to-text is set up (above).",Ce.hidden=!1);try{let n=await O("POST",`/projects/${s}/index`,{asset:t.id});y.set(n.id,{...n,asset:t.id}),w.textContent="Reading your footage. You can keep working.",W()}catch(n){w.textContent=n.message}}function K(t,{reference:n=!1}={}){let r=b=>new Promise((P,Z)=>{let G=e("li",{class:"asset"},e("span",{class:"note"},`Copying ${b.name}\u2026`),E(0,`Copying ${b.name}`));X.append(G);let J=new XMLHttpRequest;J.open("POST",`/projects/${s}/upload?name=${encodeURIComponent(b.name)}${n?"&as=reference":""}`),J.upload.onprogress=N=>{if(!N.lengthComputable)return;let V=Math.round(N.loaded*100/N.total);G.querySelector(".progress span").style.width=`${V}%`,G.querySelector(".progress").setAttribute("aria-valuenow",String(V)),G.querySelector(".note").textContent=`Copying ${b.name}\u2026 ${V}%`},J.onload=()=>{G.remove();let N={};try{N=JSON.parse(J.responseText)}catch{}J.status<300?P(N):Z(new Error(N.message??`The Edit Host answered ${J.status}.`))},J.onerror=()=>(G.remove(),Z(new Error(`${b.name} couldn't be copied.`))),J.send(b)});return(async()=>{for(let b of t)try{let P=await r(b);w.textContent=n?`Added ${b.name} as a style reference.`:`Added ${b.name}. Index it to read its words.`,n&&(ae=P.id)}catch(P){w.textContent=P.message}await A()})()}let X=e("ul",{class:"bin","aria-label":"Copying"}),z=e("input",{type:"file",multiple:!0,accept:"video/*,audio/*,.mov,.mp4,.m4v,.mkv,.wav,.mp3,.m4a,.aac,.flac,.cube",hidden:!0,id:"pick-files",onchange:()=>(K([...z.files]),z.value="")}),Q=e("input",{id:"add-path",class:"field",placeholder:"/Users/you/Movies/take.mov",autocomplete:"off"}),De=e("section",{class:"panel bin-panel","aria-label":"Bin"},e("h2",{},"Bin"),l,X,z,e("button",{type:"button",class:"btn primary wide",onclick:()=>z.click()},"Add files\u2026"),e("p",{class:"note small"},"Copied into the project's media folder; your originals aren't touched."),e("details",{class:"by-path"},e("summary",{},"Link a file by its path instead (no copy)"),e("form",{class:"row",onsubmit:async t=>{t.preventDefault();try{await O("POST",`/projects/${s}/assets`,{path:Q.value.trim()}),Q.value="",await A()}catch(n){w.textContent=n.message}}},e("label",{for:"add-path",class:"sr-only"},"Link a file by its path"),Q,e("button",{class:"btn",type:"submit"},"Link")))),ae="",se=e("ul",{class:"bin","aria-label":"Style references"}),de=e("input",{type:"file",accept:"video/*,.mov,.mp4,.m4v,.mkv,.webm",hidden:!0,id:"pick-reference",onchange:()=>{let t=[...de.files];de.value="",t.length&&confirm(`Use this video only as a style reference?
2
+
3
+ Kriya measures its pace and whether it has captions, as numbers. No picture, sound or words from it go into your video. Add only a video you're allowed to use this way.`)&&K(t,{reference:!0})}});function ut(){q(se);let t=u.filter(r=>r.kind==="reference");t.length||se.append(e("li",{class:"note"},"None yet. Add a video whose pace and captions you like."));for(let r of t)se.append(e("li",{class:"asset"},e("button",{type:"button",class:"btn",onclick:()=>F(r.id,0)},`${r.path.split(/[\\/]/).at(-1)} \xB7 reference`)));let n=(r,b,P)=>{let Z=r.value;q(r).append(e("option",{value:""},P),...b.map(G=>e("option",{value:G.id},G.path.split(/[\\/]/).at(-1)))),r.value=b.some(G=>G.id===Z)?Z:""};n(ue,t,"No reference"),ae&&t.some(r=>r.id===ae)&&(ue.value=ae,ae=""),n(ge,u.filter(r=>r.kind==="audio"),"No music")}let ee=null,re=e("p",{class:"note"}),Se=e("div"),$e=e("button",{type:"button",class:"btn primary",onclick:()=>O("POST","/runtime/setup").then(pe).catch(t=>re.textContent=t.message)},"Set up speech-to-text"),Ce=e("section",{class:"panel setup","aria-label":"Speech-to-text setup",hidden:!0},e("h2",{},"Speech-to-text"),re,Se,$e),We=t=>(t/1e6).toLocaleString(void 0,{maximumFractionDigits:0});function pe(t){ee=t;let n=ee.setup,r=n&&!n.finished;if(Ce.hidden=!ee.speech&&!r&&!n?.error,$e.hidden=!!r,$e.textContent=n?.error?"Try again":"Set up speech-to-text",q(Se),r){let b=n.total?Math.round(n.done*100/n.total):null;re.textContent=n.total?`Downloading ${n.step}: ${We(n.done)} of ${We(n.total)} MB (${b}%)`:n.line??"Setting up\u2026",Se.append(E(b,"Media Runtime setup"))}else n?.error?re.textContent=`Setup stopped: ${n.error}`:ee.speech?re.textContent="Words in the transcript need the speech model on this computer. Setting it up downloads it once; after that it works offline.":n?.finished&&(re.textContent="Ready. Index a file to read its words.")}let fe=e("input",{id:"prompt",class:"field",placeholder:"Ask for a change",autocomplete:"off"}),Me=e("span",{class:"chip selection",hidden:!0}),he=e("div",{class:"proposal","aria-live":"polite"}),je=e("ul",{class:"did","aria-label":"What I did"}),Ke=()=>{let t=_.selection();return t?{selection:{words:t},label:`Selected: ${p.words.find(n=>n.id===t[0])?.text??""}${t[0]===t[1]?"":" \u2026"}`}:f.selected?{selection:{clip:f.selected},label:`Selected: clip ${f.selected}`}:{selection:{at:g.time},label:null}},Ee=()=>{let{label:t}=Ke();Me.hidden=!t,Me.textContent=t??""};T.addEventListener("click",()=>setTimeout(Ee));function qe(t){if(q(he),f.setGhost(t?t.timeline:null),M.setGhost(t?t.timeline:null),!t)return;let n=async(r,b)=>{try{let P=await O("POST",`/projects/${s}/proposals/${t.id}`,{accept:r,...b?{only:b}:{}});if(w.textContent=P.dropped.length?`Not applied, because you changed that part: ${P.dropped.map(Z=>Z.change).join("; ")}.`:r?"Done. Undo with Cmd+Z.":"Left as it was.",r)for(let Z of b?b.map(G=>t.changes[G]):t.changes)je.prepend(e("li",{},Z))}catch(P){w.textContent=P.message}qe(null),await A()};he.append(e("p",{class:"lead"},"Proposed, not applied yet"),e("ul",{},t.changes.map((r,b)=>e("li",{},e("span",{},r),t.changes.length>1?e("button",{type:"button",class:"btn",onclick:()=>n(!0,[b])},"Only this"):null))),e("div",{class:"row"},e("button",{type:"button",class:"btn primary",onclick:()=>n(!0)},t.changes.length>1?"Accept all":"Accept"),e("button",{type:"button",class:"btn",onclick:()=>n(!1)},"Reject")))}function pt(t){let n=t.brief??{},r=e("div",{class:"proposal direct"},e("p",{class:"lead"},"That's about the whole video"),e("p",{class:"note"},`The Director can make it: the best takes, the story, ${n.captions||me.value?"captions, ":""}punch-ins and a checked master${n.seconds?`, about ${n.seconds} s`:""}.`),e("div",{class:"row"},e("button",{type:"button",class:"btn primary",onclick:()=>(r.remove(),Be(n))},"Direct it"),e("button",{type:"button",class:"btn",onclick:()=>r.remove()},"Not now")));he.append(r)}let ft=e("form",{class:"prompt",onsubmit:async t=>{t.preventDefault();let n=fe.value.trim();if(n){w.textContent="Thinking about that\u2026";try{let{proposal:r,direct:b,reason:P}=await O("POST",`/projects/${s}/ask`,{text:n,selection:Ke().selection});w.textContent=r||b?"":P??"Kriya couldn't turn that into an edit.",(r||b)&&(fe.value=""),qe(r),b&&pt(b)}catch(r){w.textContent=r.status===0||r.status>=500?"I can't reach Kriya, so I can't make changes by asking. You can still edit by hand.":r.message}}}},e("label",{for:"prompt",class:"sr-only"},"Ask for a change"),fe,e("button",{class:"btn primary",type:"submit"},"Ask")),ht={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you",not_checked:"Not checked"},Pe=e("select",{id:"make-length",class:"field select"},[["","Length: auto (30\u201360 s)"],["30","30 seconds"],["45","45 seconds"],["60","60 seconds"],["90","90 seconds"]].map(([t,n])=>e("option",{value:t},n))),me=e("select",{id:"make-captions",class:"field select"},[["","No captions"],["clean","Captions: clean"],["karaoke","Captions: karaoke"],["boxed","Captions: boxed"]].map(([t,n])=>e("option",{value:t},n))),ge=e("select",{id:"make-music",class:"field select"}),ue=e("select",{id:"make-reference",class:"field select"}),mt=(t={})=>({...Pe.value?{seconds:Number(Pe.value)}:{},...me.value?{captions:me.value}:{},...ge.value?{music:ge.value}:{},...ue.value?{reference:ue.value}:{},...t});async function Be(t){try{let n=await O("POST",`/projects/${s}/make`,{brief:mt(t)});ie=n.id,y.set(n.id,n),w.textContent="Directing your reel: reading the footage, choosing the story, cutting and checking it. You can keep working.",Ae()}catch(n){w.textContent=n.message}}let Ge=e("button",{type:"button",class:"btn primary wide",onclick:()=>Be()},"Make a reel"),Te=e("div",{class:"make-status","aria-live":"polite"});function Ae(){let t=ie?y.get(ie):null;q(Te),Ge.disabled=!!t,t&&Te.append(e("p",{class:"note"},`Making the reel\u2026 ${t.progress??0}%`),E(t.progress??0,"Making the reel"))}let gt=e("div",{class:"make"},e("label",{for:"make-length",class:"sr-only"},"Length"),Pe,e("label",{for:"make-captions",class:"sr-only"},"Captions"),me,e("label",{for:"make-music",class:"sr-only"},"Music"),ge,e("label",{for:"make-reference",class:"sr-only"},"Style reference"),e("div",{class:"row tight"},ue,de,e("button",{type:"button",class:"btn","aria-label":"Add a style reference",title:"Add a style reference",onclick:()=>de.click()},"+ Reference")),Ge,Te),ie=null;async function yt(){if(!ie)return;let t=(await O("GET","/jobs")).jobs.find(r=>r.id===ie);if(t&&y.set(t.id,t),Ae(),!t||!["done","failed","canceled"].includes(t.status))return;if(ie=null,Ae(),t.status!=="done")return w.textContent=t.error??"The reel stopped.";let n=JSON.parse(t.output);w.textContent=`${ht[n.verdict]??n.verdict}. ${n.notes.join(" ")}`;for(let r of[...n.changes].reverse())je.prepend(e("li",{},r))}let ye=e("button",{type:"button",class:"btn primary",onclick:()=>Re({type:"toggle"})},"Play"),_e=e("select",{class:"field small select","aria-label":"Preview shape",onchange:()=>g.setShape(k())},["project","16:9","9:16"].map(t=>e("option",{value:t},t==="project"?"Project shape":t))),He=e("input",{type:"range",min:"1",max:"3",step:"0.05",value:"1",class:"zoom","aria-label":"Zoom",oninput:()=>g.setZoom(Number(He.value))}),Ue=e("input",{type:"checkbox",id:"guides",onchange:()=>g.setGuides(Ue.checked)});function Re(t){if(!t)return;if(t.type==="mode")return be(t.mode);if(t.type==="prompt")return fe.focus();if(t.type==="undo")return O("PATCH",`/projects/${s}`,{undo:!0}).then(A);if(t.type==="redo")return w.textContent="Redo isn't here yet.";if(t.type==="split"){let P=ce(a,g.time);return P&&I([{op:"split",clip:P.clip,at:oe(P,g.time)}])}if(t.type==="delete")return f.selected&&I([{op:"ripple_delete",clip:f.selected}]);let n={fps:m?u.find(P=>P.id===m).facts.fps??S():S(),duration:$()},r={t:g.time,rate:g.rate},b=st(r,t,n);b.rate!==r.rate&&g.setRate(b.rate),(b.t!==r.t||t.type==="seek")&&g.seek(b.t)}function be(t){d=t,Ne("kriya-edit-mode",d),Je.dataset.mode=d;for(let n of ze.querySelectorAll("button"))n.setAttribute("aria-pressed",String(n.dataset.mode===d));f.draw(),M.draw(),d==="finish"&&B.refresh().catch(()=>{})}let ze=e("div",{class:"modes",role:"group","aria-label":"Mode"},ct.map((t,n)=>e("button",{type:"button",class:"btn",dataset:{mode:t},"aria-pressed":"false","aria-keyshortcuts":String(n+1),onclick:()=>be(t)},t[0].toUpperCase()+t.slice(1)))),Je=e("div",{class:"workspace"},lt(e("span",{class:"project-name"},h.name),ze),e("div",{class:"banner"},w,Ce),e("div",{class:"grid"},e("div",{class:"area-bin"},De,e("section",{class:"panel refs","aria-label":"Style references"},e("h2",{},"References"),se,e("button",{type:"button",class:"btn wide",onclick:()=>de.click()},"Add a reference\u2026"))),e("section",{class:"area-monitor panel","aria-label":"Monitor"},e("div",{class:"monitor-frame"},C),e("div",{class:"transport"},ye,x,i,_e,e("label",{class:"inline"},Ue," Safe zones"),e("label",{class:"inline"},"Zoom ",He))),e("aside",{class:"area-kriya panel","aria-label":"Kriya"},e("h2",{},"Direct"),gt,e("h2",{},"Ask for a change"),Me,ft,he,e("h2",{},"What I did"),je),e("section",{class:"area-transcript panel","aria-label":"Transcript"},e("h2",{},"Transcript"),e("p",{class:"note small hint"},"Click a word to jump there. Double-click (or F2) to fix a misheard word."),T),e("div",{class:"area-strip"},D),e("section",{class:"area-timeline panel","aria-label":"Timeline"},H),e("div",{class:"area-finish"},U)));q(Fe).append(Je),be(d),window.onkeydown=t=>{let n=t.target.closest?.("input, select, textarea");if(n&&t.key!=="Escape")return;if(t.key==="Escape")return n?document.activeElement?.blur():(_.clear(),f.select(null),Ee());let r=tt(t.key,{shift:t.shiftKey,mod:t.metaKey||t.ctrlKey});r&&(r.type==="toggle"&&t.target.closest?.("button")&&t.target!==ye||(t.preventDefault(),Re(r)))},setInterval(()=>d==="finish"&&B.scopes(),250);let Ye=new EventSource("/events");Ye.addEventListener("job",t=>{let n=null;try{n=JSON.parse(t.data)}catch{}n?.id&&y.set(n.id,n),d==="finish"&&B.refresh().catch(()=>{}),yt().catch(()=>{}),n&&["pending","running"].includes(n.status)?W():A().catch(()=>{})}),Ye.addEventListener("setup",t=>{try{pe({...ee??{},setup:JSON.parse(t.data)})}catch{}ee?.setup?.finished&&O("GET","/runtime").then(pe).catch(()=>{})}),O("GET","/runtime").then(pe).catch(()=>{}),await A(),window.__studio={monitor:g,act:Re,reload:A,setMode:be,get pieces(){return a}}}function dt(){let s=/^#\/p\/([0-9a-f]{16})$/.exec(location.hash);s?St(s[1]):vt()}window.addEventListener("hashchange",dt);dt();