@kriya-ai/harness 0.0.0-stage → 0.2.0
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/README.md +379 -2
- package/SAFETY.md +162 -0
- package/THIRD_PARTY_NOTICES.md +7911 -0
- package/bin/kriya.js +577 -0
- package/bundle/cordis.patch.yml +397 -0
- package/contract/SOURCE.md +15 -0
- package/contract/contract.json +1355 -0
- package/package.json +57 -4
- package/plugins/anchor/index.js +56 -0
- package/plugins/anchor/package.json +13 -0
- package/plugins/approvals/index.js +183 -0
- package/plugins/approvals/package.json +13 -0
- package/plugins/brand/DESIGN.md +112 -0
- package/plugins/brand/client.js +826 -0
- package/plugins/brand/index.js +15 -0
- package/plugins/brand/package.json +25 -0
- package/plugins/brand/src/client.js +823 -0
- package/plugins/browser/index.js +218 -0
- package/plugins/browser/package.json +13 -0
- package/plugins/budget/index.js +108 -0
- package/plugins/budget/package.json +13 -0
- package/plugins/changes/client.js +245 -0
- package/plugins/changes/index.js +75 -0
- package/plugins/changes/package.json +22 -0
- package/plugins/edit/client.js +113 -0
- package/plugins/edit/index.js +58 -0
- package/plugins/edit/package.json +23 -0
- package/plugins/fs-freshness/index.js +28 -0
- package/plugins/fs-freshness/package.json +13 -0
- package/plugins/graph/client.js +178 -0
- package/plugins/graph/index.js +4 -0
- package/plugins/graph/package.json +22 -0
- package/plugins/kriya-handoff/index.js +194 -0
- package/plugins/kriya-handoff/package.json +13 -0
- package/plugins/kriya-tools/index.js +189 -0
- package/plugins/kriya-tools/package.json +13 -0
- package/plugins/loop/index.js +743 -0
- package/plugins/loop/package.json +13 -0
- package/plugins/mirror/index.js +235 -0
- package/plugins/mirror/package.json +13 -0
- package/plugins/overview/client.js +276 -0
- package/plugins/overview/index.js +95 -0
- package/plugins/overview/package.json +22 -0
- package/plugins/preview/client.js +337 -0
- package/plugins/preview/index.js +4 -0
- package/plugins/preview/package.json +22 -0
- package/plugins/progress/client.js +290 -0
- package/plugins/progress/index.js +100 -0
- package/plugins/progress/package.json +22 -0
- package/plugins/projects/client.js +249 -0
- package/plugins/projects/index.js +30 -0
- package/plugins/projects/package.json +24 -0
- package/plugins/rea/index.js +256 -0
- package/plugins/rea/package.json +10 -0
- package/plugins/rea/skill/LICENSE +21 -0
- package/plugins/rea/skill/SKILL.md +360 -0
- package/plugins/rea/skill/references/android-applications.md +36 -0
- package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
- package/plugins/rea/skill/references/evidence-workflows.md +71 -0
- package/plugins/rea/skill/references/javascript-applications.md +218 -0
- package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
- package/plugins/rea/skill/references/runtime-observation.md +78 -0
- package/plugins/remote/index.js +297 -0
- package/plugins/remote/package.json +10 -0
- package/plugins/router/index.js +84 -0
- package/plugins/router/package.json +13 -0
- package/plugins/sessions/client.js +68 -0
- package/plugins/sessions/index.js +79 -0
- package/plugins/sessions/package.json +20 -0
- package/plugins/skills/client.js +504 -0
- package/plugins/skills/index.js +166 -0
- package/plugins/skills/package.json +23 -0
- package/src/api.js +97 -0
- package/src/browser.js +286 -0
- package/src/changes.js +191 -0
- package/src/checkpoints.js +313 -0
- package/src/daemon.js +503 -0
- package/src/doctor.js +137 -0
- package/src/edit/core/anchors.js +102 -0
- package/src/edit/core/audio.js +158 -0
- package/src/edit/core/faces.js +99 -0
- package/src/edit/core/ffmpeg.js +258 -0
- package/src/edit/core/handoff.js +220 -0
- package/src/edit/core/history.js +90 -0
- package/src/edit/core/layout.js +92 -0
- package/src/edit/core/mix.js +115 -0
- package/src/edit/core/ops.js +602 -0
- package/src/edit/core/plan.js +266 -0
- package/src/edit/core/project.d.ts +134 -0
- package/src/edit/core/project.js +307 -0
- package/src/edit/core/reframe.js +125 -0
- package/src/edit/core/solver.js +416 -0
- package/src/edit/core/time.js +110 -0
- package/src/edit/core/tonemap.js +57 -0
- package/src/edit/director/ask.js +120 -0
- package/src/edit/director/gateway.js +16 -0
- package/src/edit/director/revise.js +186 -0
- package/src/edit/engine/capabilities.js +33 -0
- package/src/edit/engine/captions.js +154 -0
- package/src/edit/engine/color.js +269 -0
- package/src/edit/engine/confine.js +67 -0
- package/src/edit/engine/dna.js +148 -0
- package/src/edit/engine/index.js +473 -0
- package/src/edit/engine/loudness.js +43 -0
- package/src/edit/engine/media.js +57 -0
- package/src/edit/engine/motion.js +281 -0
- package/src/edit/engine/packs.js +87 -0
- package/src/edit/engine/probe.js +101 -0
- package/src/edit/engine/receipt.js +123 -0
- package/src/edit/engine/tool.js +101 -0
- package/src/edit/gates/copy.js +113 -0
- package/src/edit/gates/index.js +430 -0
- package/src/edit/gates/picture.js +130 -0
- package/src/edit/gates/sound.js +58 -0
- package/src/edit/gates/speech.js +127 -0
- package/src/edit/gates/text.js +196 -0
- package/src/edit/gates/text.swift +22 -0
- package/src/edit/graph/index.js +139 -0
- package/src/edit/graph/journal.js +69 -0
- package/src/edit/graph/scheduler.js +79 -0
- package/src/edit/host/client.js +58 -0
- package/src/edit/host/deliver.js +119 -0
- package/src/edit/host/jobs.js +84 -0
- package/src/edit/host/main.js +135 -0
- package/src/edit/host/paths.js +11 -0
- package/src/edit/host/projects.js +415 -0
- package/src/edit/host/server.js +391 -0
- package/src/edit/host/taste.js +135 -0
- package/src/edit/host/tavi.js +417 -0
- package/src/edit/host/watch.js +141 -0
- package/src/edit/index/db.js +109 -0
- package/src/edit/index/index.js +236 -0
- package/src/edit/index/layers/faces.js +78 -0
- package/src/edit/index/layers/faces.swift +18 -0
- package/src/edit/index/layers/meta.js +35 -0
- package/src/edit/index/layers/music.js +146 -0
- package/src/edit/index/layers/quality.js +120 -0
- package/src/edit/index/layers/retakes.js +132 -0
- package/src/edit/index/layers/screen.js +99 -0
- package/src/edit/index/layers/shots.js +29 -0
- package/src/edit/index/layers/sound.js +42 -0
- package/src/edit/index/layers/words.js +64 -0
- package/src/edit/index/story.js +248 -0
- package/src/edit/index/views.js +71 -0
- package/src/edit/loop/governor.js +112 -0
- package/src/edit/loop/loop.js +69 -0
- package/src/edit/loop/make.js +115 -0
- package/src/edit/loop/repair.js +97 -0
- package/src/edit/loop/replay.js +32 -0
- package/src/edit/recipes/multicam.js +461 -0
- package/src/edit/recipes/reel.js +202 -0
- package/src/edit/recipes/short-from-long.js +237 -0
- package/src/edit/recipes/tutorial.js +137 -0
- package/src/edit/recipes/youtube.js +155 -0
- package/src/edit/runtime/cli.js +126 -0
- package/src/edit/runtime/doctor.js +122 -0
- package/src/edit/runtime/fetch.js +15 -0
- package/src/edit/runtime/licences.js +88 -0
- package/src/edit/runtime/manifest.js +73 -0
- package/src/edit/runtime/setup.js +252 -0
- package/src/failure.js +69 -0
- package/src/gateway-proxy.js +213 -0
- package/src/intent.js +130 -0
- package/src/launch.js +315 -0
- package/src/live.js +81 -0
- package/src/local-skills.js +284 -0
- package/src/login.js +82 -0
- package/src/loop.js +428 -0
- package/src/modes.js +128 -0
- package/src/overview.js +71 -0
- package/src/paths.js +30 -0
- package/src/profiles.js +92 -0
- package/src/projects.js +104 -0
- package/src/recon.js +244 -0
- package/src/rules.js +139 -0
- package/src/runner.bundle.js +21172 -0
- package/src/sentinel.js +248 -0
- package/src/skill-switches.js +130 -0
- package/src/store.js +58 -0
- package/src/strict.js +124 -0
- package/src/verify.js +659 -0
- package/src/world.js +268 -0
- package/studio/dist/index.html +14 -0
- package/studio/dist/studio.css +163 -0
- package/studio/dist/studio.js +1 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// The graph runtime (EDIT_LOOP §4; Mokhov, Mitchell, Peyton Jones, Build Systems à
|
|
2
|
+
// la Carte). A node is a function of what it reads. Each result stores a verifying
|
|
3
|
+
// trace: the hashes it read and the hash it produced. Nothing runs until demanded;
|
|
4
|
+
// an unchanged output stops the work downstream. It knows nothing of what a node means.
|
|
5
|
+
|
|
6
|
+
import { createHash } from "node:crypto"
|
|
7
|
+
|
|
8
|
+
import { createScheduler, DEFAULT_SLOTS } from "./scheduler.js"
|
|
9
|
+
|
|
10
|
+
export class Interrupted extends Error {
|
|
11
|
+
constructor(message = "Interrupted") {
|
|
12
|
+
super(message)
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const sorted = (_, value) => (value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1))) : value)
|
|
17
|
+
export const hashOf = (value) => createHash("sha256").update(JSON.stringify(value ?? null, sorted)).digest("hex")
|
|
18
|
+
|
|
19
|
+
const idOf = (name, key) => (key ? `${name}:${key}` : name)
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {{ journal: ReturnType<import("./journal.js").openJournal>, nodes: Record<string, { version: number, resources?: string[], valid?: (value: any) => boolean, run: (ctx: object) => Promise<any> }>, slots?: Record<string, number>, scheduler?: ReturnType<typeof createScheduler> }} options
|
|
23
|
+
* One Host shares one scheduler across its projects' graphs.
|
|
24
|
+
*/
|
|
25
|
+
export function createGraph({ journal, nodes, slots = DEFAULT_SLOTS, scheduler = createScheduler(slots) }) {
|
|
26
|
+
const owner = Symbol("graph") // Turns pass between graphs on a shared scheduler
|
|
27
|
+
const inputs = new Map()
|
|
28
|
+
const known = new Map() // id → { round, hash, value }, so one round checks each node once
|
|
29
|
+
const flying = new Map()
|
|
30
|
+
let round = 1
|
|
31
|
+
|
|
32
|
+
const inputHash = (name) => inputs.get(name)?.hash ?? hashOf(null)
|
|
33
|
+
|
|
34
|
+
async function fresh(trace, node, ctx) {
|
|
35
|
+
if (!trace || trace.version !== node.version) return false
|
|
36
|
+
if (node.valid && !node.valid(trace.value)) return false
|
|
37
|
+
// In the order they were read: a changed dep may mean later ones no longer apply
|
|
38
|
+
for (const dep of trace.deps) {
|
|
39
|
+
const hash = dep.input ? inputHash(dep.input) : (await build(dep.name, dep.key, ctx)).hash
|
|
40
|
+
if (hash !== dep.hash) return false
|
|
41
|
+
}
|
|
42
|
+
return true
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function execute(name, key, id, node, ctx) {
|
|
46
|
+
const resources = node.resources ?? []
|
|
47
|
+
if (ctx.speculate && resources.includes("model")) throw new Interrupted("Speculation never spends model tokens")
|
|
48
|
+
const kind = name
|
|
49
|
+
const job = ctx.job ?? 0
|
|
50
|
+
const controller = new AbortController()
|
|
51
|
+
const signal = ctx.signal ? AbortSignal.any([ctx.signal, controller.signal]) : controller.signal
|
|
52
|
+
const options = { speculate: ctx.speculate, signal, owner, preempt: () => controller.abort(new Interrupted("Real work needed this slot")) }
|
|
53
|
+
let release = await scheduler.acquire(resources, options)
|
|
54
|
+
const deps = []
|
|
55
|
+
// A node gives up its slots while it waits on another, so a chain can't deadlock
|
|
56
|
+
const waiting = async (work) => {
|
|
57
|
+
release()
|
|
58
|
+
try {
|
|
59
|
+
return await work()
|
|
60
|
+
} finally {
|
|
61
|
+
release = await scheduler.acquire(resources, options)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
journal.step({ job, id, kind, status: "running", resources: resources.join(",") })
|
|
65
|
+
try {
|
|
66
|
+
const value = await node.run({
|
|
67
|
+
key,
|
|
68
|
+
job: ctx.job,
|
|
69
|
+
signal,
|
|
70
|
+
input: async (input) => {
|
|
71
|
+
deps.push({ input, hash: inputHash(input) })
|
|
72
|
+
return inputs.get(input)?.value
|
|
73
|
+
},
|
|
74
|
+
need: (other, otherKey = "") =>
|
|
75
|
+
waiting(async () => {
|
|
76
|
+
const result = await build(other, otherKey, { ...ctx, stack: [...ctx.stack, id] })
|
|
77
|
+
deps.push({ name: other, key: otherKey, hash: result.hash })
|
|
78
|
+
return result.value
|
|
79
|
+
}),
|
|
80
|
+
})
|
|
81
|
+
const hash = hashOf(value)
|
|
82
|
+
journal.saveTrace({ id, version: node.version, deps, hash, value })
|
|
83
|
+
journal.step({ job, id, kind, status: "done", outputKey: hash })
|
|
84
|
+
return { hash, value }
|
|
85
|
+
} catch (error) {
|
|
86
|
+
journal.step({ job, id, kind, status: error instanceof Interrupted ? "pending" : "failed", log: String(error?.message ?? error) })
|
|
87
|
+
throw error
|
|
88
|
+
} finally {
|
|
89
|
+
release()
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function compute(name, key, id, node, ctx) {
|
|
94
|
+
const trace = journal.trace(id)
|
|
95
|
+
const reusable = await fresh(trace, node, { ...ctx, stack: [...ctx.stack, id] })
|
|
96
|
+
const result = reusable ? { hash: trace.hash, value: trace.value } : await execute(name, key, id, node, ctx)
|
|
97
|
+
known.set(id, { round, ...result })
|
|
98
|
+
return result
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function build(name, key, ctx) {
|
|
102
|
+
const node = nodes[name]
|
|
103
|
+
if (!node) throw new Error(`no node "${name}"`)
|
|
104
|
+
const id = idOf(name, key)
|
|
105
|
+
if (ctx.stack.includes(id)) throw new Error(`a cycle through ${id}`)
|
|
106
|
+
const memo = known.get(id)
|
|
107
|
+
if (memo?.round === round) return memo
|
|
108
|
+
const running = flying.get(id)
|
|
109
|
+
if (running) {
|
|
110
|
+
try {
|
|
111
|
+
return await running
|
|
112
|
+
} catch (error) {
|
|
113
|
+
// Real work joined speculation that lost its slot: do it properly
|
|
114
|
+
if (error instanceof Interrupted && !ctx.speculate) return build(name, key, ctx)
|
|
115
|
+
throw error
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const work = compute(name, key, id, node, ctx).finally(() => flying.delete(id))
|
|
119
|
+
flying.set(id, work)
|
|
120
|
+
return work
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
/** Sets a leaf value. An equal value changes nothing. */
|
|
125
|
+
set(name, value) {
|
|
126
|
+
const hash = hashOf(value)
|
|
127
|
+
if (inputHash(name) !== hash) round++
|
|
128
|
+
inputs.set(name, { value, hash })
|
|
129
|
+
},
|
|
130
|
+
/** Forces the next demand to re-check traces, as after a cache eviction. */
|
|
131
|
+
touch() {
|
|
132
|
+
round++
|
|
133
|
+
},
|
|
134
|
+
/** @param {string} name @param {string} [key] @param {{ speculate?: boolean, job?: number, signal?: AbortSignal }} [options] */
|
|
135
|
+
async demand(name, key = "", { speculate = false, job, signal } = {}) {
|
|
136
|
+
return (await build(name, key, { stack: [], speculate, job, signal })).value
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// journal.sqlite (DATA_MODEL §3.2): jobs, steps, measurements, and the graph's
|
|
2
|
+
// verifying traces. On open, a step left `running` by a crash becomes `pending`.
|
|
3
|
+
|
|
4
|
+
import { DatabaseSync } from "node:sqlite"
|
|
5
|
+
|
|
6
|
+
const SCHEMA = `
|
|
7
|
+
create table if not exists jobs (id integer primary key, kind text not null, project_version text, status text not null default 'pending', progress integer not null default 0, error text, started_at text, finished_at text, dispatch text, request text);
|
|
8
|
+
create table if not exists steps (job integer not null default 0, id text not null, kind text not null, input_hash text, status text not null, attempts integer not null default 0, resources text not null default '', output_key text, log text, primary key (job, id));
|
|
9
|
+
create table if not exists calls (job integer not null, task text, tier text, input_tokens integer, cached_tokens integer, output_tokens integer, ms integer, result text);
|
|
10
|
+
create table if not exists answers (job integer not null, n integer not null, task text not null, source text not null, value text not null, primary key (job, n));
|
|
11
|
+
create table if not exists measurements (job integer not null, gate text not null, key text not null, value real, at_time integer);
|
|
12
|
+
create table if not exists traces (id text primary key, version integer not null, deps text not null, output_hash text not null, value text not null);
|
|
13
|
+
`
|
|
14
|
+
|
|
15
|
+
export function openJournal(file) {
|
|
16
|
+
const db = new DatabaseSync(file)
|
|
17
|
+
if (file !== ":memory:") db.exec("pragma journal_mode = wal")
|
|
18
|
+
db.exec(SCHEMA)
|
|
19
|
+
db.exec("update steps set status = 'pending' where status = 'running'")
|
|
20
|
+
db.exec("update jobs set status = 'pending' where status = 'running'")
|
|
21
|
+
|
|
22
|
+
const plain = (row) => (row ? { ...row } : null)
|
|
23
|
+
return {
|
|
24
|
+
close: () => db.close(),
|
|
25
|
+
|
|
26
|
+
trace(id) {
|
|
27
|
+
const row = db.prepare("select * from traces where id = ?").get(id)
|
|
28
|
+
return row ? { id: row.id, version: row.version, deps: JSON.parse(row.deps), hash: row.output_hash, value: JSON.parse(row.value) } : null
|
|
29
|
+
},
|
|
30
|
+
saveTrace({ id, version, deps, hash, value }) {
|
|
31
|
+
db.prepare("insert or replace into traces (id, version, deps, output_hash, value) values (?, ?, ?, ?, ?)").run(id, version, JSON.stringify(deps), hash, JSON.stringify(value))
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
step({ job = 0, id, kind, status, resources = "", outputKey = null, log = null }) {
|
|
35
|
+
db.prepare(
|
|
36
|
+
`insert into steps (job, id, kind, status, attempts, resources, output_key, log) values (?, ?, ?, ?, ?, ?, ?, ?)
|
|
37
|
+
on conflict (job, id) do update set status = excluded.status, attempts = attempts + excluded.attempts, output_key = coalesce(excluded.output_key, output_key), log = excluded.log`,
|
|
38
|
+
).run(job, id, kind, status, status === "running" ? 1 : 0, resources, outputKey, log)
|
|
39
|
+
},
|
|
40
|
+
steps: (job) => (job === undefined ? db.prepare("select * from steps").all() : db.prepare("select * from steps where job = ?").all(job)).map(plain),
|
|
41
|
+
|
|
42
|
+
addJob({ kind, projectVersion = null, dispatch = null, request = null }) {
|
|
43
|
+
return Number(db.prepare("insert into jobs (kind, project_version, dispatch, request) values (?, ?, ?, ?)").run(kind, projectVersion, dispatch, request === null ? null : JSON.stringify(request)).lastInsertRowid)
|
|
44
|
+
},
|
|
45
|
+
setJob(id, fields) {
|
|
46
|
+
const keys = Object.keys(fields)
|
|
47
|
+
db.prepare(`update jobs set ${keys.map((key) => `${key} = ?`).join(", ")} where id = ?`).run(...keys.map((key) => fields[key]), id)
|
|
48
|
+
},
|
|
49
|
+
job: (id) => plain(db.prepare("select * from jobs where id = ?").get(id)),
|
|
50
|
+
jobs: (status) => (status ? db.prepare("select * from jobs where status = ? order by id").all(status) : db.prepare("select * from jobs order by id").all()).map(plain),
|
|
51
|
+
|
|
52
|
+
/** A Director call: what was asked, how big, how it went; never the prompt (§3.2). */
|
|
53
|
+
call({ job = 0, task, tier, input_tokens = null, cached_tokens = null, output_tokens = null, ms = null, result }) {
|
|
54
|
+
db.prepare("insert into calls (job, task, tier, input_tokens, cached_tokens, output_tokens, ms, result) values (?, ?, ?, ?, ?, ?, ?, ?)").run(job, task, tier, input_tokens, cached_tokens, output_tokens, ms, result)
|
|
55
|
+
},
|
|
56
|
+
calls: (job) => db.prepare("select * from calls where job = ? order by rowid").all(job).map(plain),
|
|
57
|
+
/** A Director slot's final answer, for `kriya edit replay` (EDIT_LOOP §10): the value, never the prompt. */
|
|
58
|
+
answer({ job = 0, task, source, value }) {
|
|
59
|
+
const n = db.prepare("select count(*) as n from answers where job = ?").get(job).n
|
|
60
|
+
db.prepare("insert into answers (job, n, task, source, value) values (?, ?, ?, ?, ?)").run(job, n, task, source, JSON.stringify(value))
|
|
61
|
+
},
|
|
62
|
+
answers: (job) => db.prepare("select task, source, value from answers where job = ? order by n").all(job).map(plain),
|
|
63
|
+
|
|
64
|
+
measure(job, { gate, key, value, at = null }) {
|
|
65
|
+
db.prepare("insert into measurements (job, gate, key, value, at_time) values (?, ?, ?, ?, ?)").run(job, gate, key, value, at)
|
|
66
|
+
},
|
|
67
|
+
measurements: (job) => db.prepare("select * from measurements where job = ?").all(job).map(plain),
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Slots for `cpu`, `gpu`, `encoder`, `chrome`, `model`, `disk` (ARCHITECTURE §8).
|
|
2
|
+
// Real work goes first, then speculation. Within that, turns pass between owners, so
|
|
3
|
+
// a long job can't starve a short one, and each owner's work keeps its arrival order.
|
|
4
|
+
// A waiter takes all its resources at once or none, so two nodes can't deadlock.
|
|
5
|
+
|
|
6
|
+
import { availableParallelism } from "node:os"
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_SLOTS = { cpu: Math.max(2, availableParallelism() - 2), gpu: 1, encoder: 2, chrome: 1, model: 2, disk: 2 }
|
|
9
|
+
|
|
10
|
+
export function createScheduler(slots = DEFAULT_SLOTS) {
|
|
11
|
+
const held = new Map()
|
|
12
|
+
const holders = new Set()
|
|
13
|
+
const waiting = []
|
|
14
|
+
const served = new Map() // owner → when it last got a slot
|
|
15
|
+
let turn = 0
|
|
16
|
+
|
|
17
|
+
const busy = (resource) => held.get(resource) ?? 0
|
|
18
|
+
const free = (resources) => resources.every((resource) => busy(resource) < (slots[resource] ?? 1))
|
|
19
|
+
|
|
20
|
+
function grant(waiter) {
|
|
21
|
+
served.set(waiter.owner, ++turn)
|
|
22
|
+
for (const resource of waiter.resources) held.set(resource, busy(resource) + 1)
|
|
23
|
+
const holder = { resources: waiter.resources, speculate: waiter.speculate, preempt: waiter.preempt }
|
|
24
|
+
holders.add(holder)
|
|
25
|
+
waiter.done(() => {
|
|
26
|
+
if (!holders.delete(holder)) return
|
|
27
|
+
for (const resource of holder.resources) held.set(resource, busy(resource) - 1)
|
|
28
|
+
pump()
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// shortcut: a waiter for several slots can be overtaken by single-slot ones, fine until a node needs two scarce slots at once
|
|
33
|
+
function pump() {
|
|
34
|
+
for (;;) {
|
|
35
|
+
const ready = waiting.filter((waiter) => free(waiter.resources))
|
|
36
|
+
if (ready.length === 0) return
|
|
37
|
+
const rank = (waiter) => [waiter.speculate ? 1 : 0, served.get(waiter.owner) ?? 0, waiting.indexOf(waiter)]
|
|
38
|
+
const next = ready.reduce((best, waiter) => {
|
|
39
|
+
const [a, b] = [rank(waiter), rank(best)]
|
|
40
|
+
return a[0] - b[0] || a[1] - b[1] || a[2] - b[2] ? (a[0] - b[0] || a[1] - b[1] || a[2] - b[2]) < 0 ? waiter : best : best
|
|
41
|
+
})
|
|
42
|
+
waiting.splice(waiting.indexOf(next), 1)
|
|
43
|
+
grant(next)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function preempt(resources) {
|
|
48
|
+
for (const holder of holders) {
|
|
49
|
+
if (holder.speculate && holder.resources.some((resource) => resources.includes(resource))) holder.preempt?.()
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {string[]} resources
|
|
55
|
+
* @param {{ speculate?: boolean, preempt?: () => void, signal?: AbortSignal, owner?: unknown }} [options]
|
|
56
|
+
* @returns {Promise<() => void>} the release function
|
|
57
|
+
*/
|
|
58
|
+
function acquire(resources, { speculate = false, preempt: onPreempt, signal, owner } = {}) {
|
|
59
|
+
return new Promise((done, fail) => {
|
|
60
|
+
if (signal?.aborted) return fail(signal.reason)
|
|
61
|
+
const waiter = { resources, speculate, preempt: onPreempt, done, owner }
|
|
62
|
+
waiting.push(waiter)
|
|
63
|
+
signal?.addEventListener(
|
|
64
|
+
"abort",
|
|
65
|
+
() => {
|
|
66
|
+
const at = waiting.indexOf(waiter)
|
|
67
|
+
if (at === -1) return
|
|
68
|
+
waiting.splice(at, 1)
|
|
69
|
+
fail(signal.reason)
|
|
70
|
+
},
|
|
71
|
+
{ once: true },
|
|
72
|
+
)
|
|
73
|
+
pump()
|
|
74
|
+
if (waiting.includes(waiter) && !speculate) preempt(resources)
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return { acquire, busy }
|
|
79
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Reaching the Host from anything else: one socket, mode 0600, no port, no cookie.
|
|
2
|
+
// `ensureHost` starts one, detached, so it outlives whoever asked (EH-05).
|
|
3
|
+
|
|
4
|
+
import { spawn } from "node:child_process"
|
|
5
|
+
import { mkdirSync, openSync } from "node:fs"
|
|
6
|
+
import { request } from "node:http"
|
|
7
|
+
import { join } from "node:path"
|
|
8
|
+
|
|
9
|
+
import { kriyaHome } from "../../paths.js"
|
|
10
|
+
import { editHome, logPath, socketPath } from "./paths.js"
|
|
11
|
+
|
|
12
|
+
const START_MS = 15_000
|
|
13
|
+
|
|
14
|
+
/** @returns {Promise<any>} the parsed answer; rejects when the Host isn't there or refuses */
|
|
15
|
+
export function hostCall(home, method, path, body) {
|
|
16
|
+
return new Promise((done, fail) => {
|
|
17
|
+
const data = body === undefined ? null : JSON.stringify(body)
|
|
18
|
+
const req = request({ socketPath: socketPath(home), method, path, headers: { host: "kriya-edit", ...(data ? { "content-type": "application/json" } : {}) } }, (res) => {
|
|
19
|
+
const chunks = []
|
|
20
|
+
res.on("data", (chunk) => chunks.push(chunk))
|
|
21
|
+
res.on("end", () => {
|
|
22
|
+
const text = Buffer.concat(chunks).toString()
|
|
23
|
+
const json = text ? JSON.parse(text) : null
|
|
24
|
+
if (res.statusCode >= 400) fail(new Error(json?.message ?? `The Edit Host answered ${res.statusCode}.`))
|
|
25
|
+
else done(json)
|
|
26
|
+
})
|
|
27
|
+
})
|
|
28
|
+
req.on("error", fail)
|
|
29
|
+
if (data) req.write(data)
|
|
30
|
+
req.end()
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const contact = (home) => hostCall(home, "GET", "/internal/info").catch(() => null)
|
|
35
|
+
|
|
36
|
+
/** The running Host, started if need be. @returns {Promise<{ pid: number, port: number }>} */
|
|
37
|
+
export async function ensureHost({ env = process.env, home = kriyaHome() } = {}) {
|
|
38
|
+
const live = await contact(home)
|
|
39
|
+
if (live) return live
|
|
40
|
+
mkdirSync(editHome(home), { recursive: true })
|
|
41
|
+
const log = openSync(logPath(home), "a")
|
|
42
|
+
const main = join(import.meta.dirname, "main.js")
|
|
43
|
+
spawn(process.execPath, [main], { detached: true, stdio: ["ignore", log, log], env: { ...env, KRIYA_HOME: home } }).unref()
|
|
44
|
+
const started = Date.now()
|
|
45
|
+
while (Date.now() - started < START_MS) {
|
|
46
|
+
const answer = await contact(home)
|
|
47
|
+
if (answer) return answer
|
|
48
|
+
await new Promise((done) => setTimeout(done, 40))
|
|
49
|
+
}
|
|
50
|
+
throw new Error(`The Edit Host didn't start. See ${logPath(home)}.`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Stops the Host and waits until it's gone. */
|
|
54
|
+
export async function stopHost(home = kriyaHome()) {
|
|
55
|
+
await hostCall(home, "POST", "/internal/stop").catch(() => null)
|
|
56
|
+
const started = Date.now()
|
|
57
|
+
while ((await contact(home)) && Date.now() - started < START_MS) await new Promise((done) => setTimeout(done, 25))
|
|
58
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// What a delivered export carries (ED10): its receipt and its report beside it, and
|
|
2
|
+
// the speech recogniser the gates may trust. A recogniser counts as verified only
|
|
3
|
+
// when the signed manifest ships its weights as an artifact (EB-11), never because a
|
|
4
|
+
// folder with the right name exists.
|
|
5
|
+
|
|
6
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
|
7
|
+
import { dirname, join, resolve, sep } from "node:path"
|
|
8
|
+
|
|
9
|
+
import { thumbArgs } from "../core/ffmpeg.js"
|
|
10
|
+
import { handoffManifest, timelineMarkers, toEdl, toFcpxml, toOtio, toSrt } from "../core/handoff.js"
|
|
11
|
+
import { solve } from "../core/solver.js"
|
|
12
|
+
import { EngineFailure } from "../engine/tool.js"
|
|
13
|
+
import { chapterList } from "../index/story.js"
|
|
14
|
+
import { makeReceipt, reportHtml, reportPath, writeReceipt } from "../engine/receipt.js"
|
|
15
|
+
import { childEnv } from "../runtime/setup.js"
|
|
16
|
+
import { MODEL, readWords, recogniser, speechArgs, transcribeArgs } from "../index/layers/words.js"
|
|
17
|
+
|
|
18
|
+
/** (file) → words heard, or undefined when this runtime has no verified recogniser. */
|
|
19
|
+
export function verifiedRecogniser(runtime, { run, work, language = "en", platform = `${process.platform}-${process.arch}` }) {
|
|
20
|
+
const shipped = runtime?.manifest?.platforms?.[platform]?.artifacts?.some((a) => a.id === MODEL)
|
|
21
|
+
if (!shipped) return undefined
|
|
22
|
+
const engine = recogniser(runtime, platform)
|
|
23
|
+
if (engine.missing) return undefined
|
|
24
|
+
return async (file) => {
|
|
25
|
+
mkdirSync(work, { recursive: true })
|
|
26
|
+
const dir = mkdtempSync(join(work, "heard-"))
|
|
27
|
+
try {
|
|
28
|
+
const audio = join(dir, "speech.wav")
|
|
29
|
+
await run("ffmpeg", speechArgs(file, audio), { timeoutMs: 600_000 })
|
|
30
|
+
const env = { ...childEnv(), HF_HUB_OFFLINE: "1", HF_HUB_DISABLE_TELEMETRY: "1" }
|
|
31
|
+
return readWords(await run(engine.python, transcribeArgs(engine, audio, language), { env, timeoutMs: 1_800_000 }))
|
|
32
|
+
} finally {
|
|
33
|
+
rmSync(dir, { recursive: true, force: true })
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A contact sheet of a file, as JPEG bytes; null if it can't be made. */
|
|
39
|
+
async function sheetOf(file, seconds, { run, work }) {
|
|
40
|
+
const out = join(work, `sheet-${Math.random().toString(36).slice(2)}.jpg`)
|
|
41
|
+
try {
|
|
42
|
+
await run("ffmpeg", thumbArgs({ source: file, output: out, every: Math.max(1, Math.ceil(seconds / 20)), columns: 5, rows: 4 }), { timeoutMs: 300_000 })
|
|
43
|
+
return readFileSync(out)
|
|
44
|
+
} catch {
|
|
45
|
+
return null
|
|
46
|
+
} finally {
|
|
47
|
+
rmSync(out, { force: true })
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Writes `<name>.receipt.json` and `<name>.report.html` beside the export.
|
|
53
|
+
* @returns {Promise<{ receipt: string, report: string, verdict: string }>}
|
|
54
|
+
*/
|
|
55
|
+
export async function writeDelivery({ file, title, project, parent, plan, sourcePath, tools, gates, verdict, calls, changes, notes, repairs = [], beforeFrom, run, work }) {
|
|
56
|
+
mkdirSync(work, { recursive: true })
|
|
57
|
+
const used = new Set([...plan.segments.flatMap((s) => [...s.node.picture, ...s.node.overlays].map((i) => i.asset)), ...plan.audio.items.map((i) => i.asset)])
|
|
58
|
+
const sources = Object.fromEntries([...used].map((id) => [id, sourcePath(id)]))
|
|
59
|
+
const receipt = await makeReceipt({ file, project, parent, plan, sources, tools, gates, verdict, calls, run })
|
|
60
|
+
const receiptFile = writeReceipt(file, receipt)
|
|
61
|
+
const seconds = plan.duration / 705_600_000
|
|
62
|
+
const before = beforeFrom ? await sheetOf(beforeFrom, seconds * 2, { run, work }) : null
|
|
63
|
+
const after = await sheetOf(file, seconds, { run, work })
|
|
64
|
+
const rights = project.assets.filter((a) => used.has(a.id)).map((a) => ({ id: a.id, rights: a.rights, role: a.role }))
|
|
65
|
+
const report = reportPath(file)
|
|
66
|
+
writeFileSync(report, reportHtml({ receipt, title, before, after, changes, notes, rights, repairs }))
|
|
67
|
+
return { receipt: receiptFile, report, verdict: receipt.verdict }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A handoff package (EDIT_ENGINE §11): the current cut as OTIO, FCPXML, CMX 3600 EDL and
|
|
72
|
+
* SRT in a new folder under the exports folder, chapters as markers, the media linked in
|
|
73
|
+
* at the relative paths those files name, and a manifest of what to relink and what a
|
|
74
|
+
* format couldn't carry. Sources are linked, never copied or written.
|
|
75
|
+
* shortcut: media are symbolic links to the person's files, so a package moved to another computer relinks from the manifest; copying is not built
|
|
76
|
+
* @returns {{ folder: string, files: string[], media: number, omitted: object[], chapters: { name: string, at: number }[] }}
|
|
77
|
+
*/
|
|
78
|
+
export function writeHandoff({ project, index, exportsDir, sourcePath }) {
|
|
79
|
+
const timeline = solve(project, index)
|
|
80
|
+
if (!timeline.picture.length) throw new EngineFailure("input", "empty", "There is nothing on the timeline to hand off yet.")
|
|
81
|
+
const { markers, lost } = timelineMarkers(project, index, timeline)
|
|
82
|
+
const slug = project.name.normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "").slice(0, 40) || "edit"
|
|
83
|
+
mkdirSync(exportsDir, { recursive: true })
|
|
84
|
+
let folder
|
|
85
|
+
for (let n = 1; ; n++) {
|
|
86
|
+
folder = join(exportsDir, `${slug}-handoff${n === 1 ? "" : `-${n}`}`)
|
|
87
|
+
try {
|
|
88
|
+
mkdirSync(folder)
|
|
89
|
+
break
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error.code !== "EEXIST") throw error
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const fcpxml = toFcpxml(project, timeline, markers)
|
|
95
|
+
const edl = toEdl(project, timeline)
|
|
96
|
+
const files = { [`${slug}.otio`]: toOtio(project, timeline, markers), [`${slug}.fcpxml`]: fcpxml.text, [`${slug}.edl`]: edl.text }
|
|
97
|
+
if (timeline.captions.length) files[`${slug}.srt`] = toSrt(timeline)
|
|
98
|
+
if (markers.length) files["chapters.txt"] = `${chapterList(markers.map((m) => ({ at: m.at, title: m.name })))}\n`
|
|
99
|
+
const omitted = [
|
|
100
|
+
...fcpxml.omitted.map((o) => ({ format: "fcpxml", ...o })),
|
|
101
|
+
...edl.omitted.map((o) => ({ format: "edl", ...o })),
|
|
102
|
+
...lost.map((o) => ({ format: "all", ...o })),
|
|
103
|
+
...(timeline.captions.length ? [] : [{ format: "srt", reason: "this cut has no captions, so there is no SRT" }]),
|
|
104
|
+
]
|
|
105
|
+
const media = handoffManifest(project, timeline)
|
|
106
|
+
for (const entry of media) {
|
|
107
|
+
const target = resolve(folder, entry.path)
|
|
108
|
+
if (!target.startsWith(folder + sep)) {
|
|
109
|
+
omitted.push({ format: "all", asset: entry.asset, reason: "its path would leave the package, so it isn't linked; relink it by hand" })
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
113
|
+
symlinkSync(sourcePath(entry.asset), target)
|
|
114
|
+
}
|
|
115
|
+
for (const [name, text] of Object.entries(files)) writeFileSync(join(folder, name), text, { flag: "wx" })
|
|
116
|
+
const manifest = { kriya: "handoff", version: 1, name: project.name, fps: timeline.fps, duration: timeline.duration, files: Object.keys(files), media, chapters: markers, omitted }
|
|
117
|
+
writeFileSync(join(folder, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`, { flag: "wx" })
|
|
118
|
+
return { folder, files: [...Object.keys(files), "manifest.json"], media: media.length, omitted, chapters: markers }
|
|
119
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The Host owns jobs (EDD-03): each lives in its project's journal, so a job in
|
|
2
|
+
// progress when the Host dies resumes on the next start with no finished node redone.
|
|
3
|
+
|
|
4
|
+
import { projectAt } from "../core/history.js"
|
|
5
|
+
|
|
6
|
+
// A render is of the version it was asked for, not whatever the project has become by
|
|
7
|
+
// the time it runs: an edit or an undo right after "Render" changed the film (found by EG-5)
|
|
8
|
+
function versionOf(state, number) {
|
|
9
|
+
const at = state.journal.job(number).project_version ?? null
|
|
10
|
+
return at === state.log.head ? state.log.current : projectAt(state.log, at, { index: state.index })
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
|
|
14
|
+
const running = new Map() // "<project>.<n>" → AbortController
|
|
15
|
+
|
|
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 })
|
|
18
|
+
|
|
19
|
+
async function run(state, number, request) {
|
|
20
|
+
const id = idOf(state, number)
|
|
21
|
+
const controller = new AbortController()
|
|
22
|
+
running.set(id, controller)
|
|
23
|
+
const update = (fields, error) => {
|
|
24
|
+
state.journal.setJob(number, fields)
|
|
25
|
+
const current = view(state, state.journal.job(number))
|
|
26
|
+
emit("job", current)
|
|
27
|
+
// A job from Kriya says how it's going to Kriya too (TAVI_INTEGRATION §4)
|
|
28
|
+
if (request.dispatch) void Promise.resolve(onDispatch?.(request, current, error)).catch((failure) => log(`job ${id}: report failed: ${failure.name}`))
|
|
29
|
+
}
|
|
30
|
+
update({ status: "running", started_at: new Date().toISOString() })
|
|
31
|
+
try {
|
|
32
|
+
const onStep = (done, total) => update({ progress: Math.floor((done * 100) / total) })
|
|
33
|
+
const output =
|
|
34
|
+
request.kind === "index"
|
|
35
|
+
? JSON.stringify(await projects.indexAsset(state, request.asset, { signal: controller.signal, onStep }))
|
|
36
|
+
: request.kind === "make"
|
|
37
|
+
? JSON.stringify(await projects.make(state, request, { job: number, signal: controller.signal, onStep, ...(request.dispatch && beforeStory && { beforeStory: (...args) => beforeStory(request, ...args) }) }))
|
|
38
|
+
: request.kind === "revise"
|
|
39
|
+
? JSON.stringify(await projects.revise(state, request, { job: number, signal: controller.signal, onStep }))
|
|
40
|
+
: request.kind === "replay"
|
|
41
|
+
? JSON.stringify(await projects.replay(state, request.of, { job: number, signal: controller.signal, onStep }))
|
|
42
|
+
: (await state.engine.render({ ...request, job: number, signal: controller.signal, onStep, project: request.project ?? versionOf(state, number) })).file
|
|
43
|
+
update({ status: "done", progress: 100, dispatch: output, finished_at: new Date().toISOString() })
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (controller.signal.aborted) update({ status: "canceled", finished_at: new Date().toISOString() })
|
|
46
|
+
else {
|
|
47
|
+
log(`job ${id} failed: ${error.reason ?? error.name}`)
|
|
48
|
+
update({ status: "failed", error: error.message, finished_at: new Date().toISOString() }, error)
|
|
49
|
+
}
|
|
50
|
+
} finally {
|
|
51
|
+
running.delete(id)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
count: () => running.size,
|
|
57
|
+
|
|
58
|
+
start(state, request) {
|
|
59
|
+
const number = state.journal.addJob({ kind: request.kind ?? "render", projectVersion: state.log.head, request })
|
|
60
|
+
void run(state, number, request)
|
|
61
|
+
return view(state, state.journal.job(number))
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
async list() {
|
|
65
|
+
const jobs = []
|
|
66
|
+
await projects.each((state) => {
|
|
67
|
+
jobs.push(...state.journal.jobs().map((row) => view(state, row)))
|
|
68
|
+
})
|
|
69
|
+
return jobs
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
cancel(id) {
|
|
73
|
+
const controller = running.get(id)
|
|
74
|
+
controller?.abort(new Error("Canceled"))
|
|
75
|
+
return !!controller
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
/** What a crash left unfinished. */
|
|
79
|
+
resume: () =>
|
|
80
|
+
projects.each((state) => {
|
|
81
|
+
for (const row of state.journal.jobs("pending")) void run(state, row.id, JSON.parse(row.request))
|
|
82
|
+
}),
|
|
83
|
+
}
|
|
84
|
+
}
|