@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.
Files changed (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,252 @@
1
+ // `kriya edit setup`: installs a signed runtime into ~/.kriya/media/<version>/.
2
+ // Versions sit side by side; `.complete` is written last and `current.json` moves
3
+ // only after it, so a failed install never touches the working version.
4
+
5
+ import { execFile } from "node:child_process"
6
+ import { createHash } from "node:crypto"
7
+ import { cpSync, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statfsSync, statSync, writeFileSync } from "node:fs"
8
+ import { once } from "node:events"
9
+ import { dirname, join } from "node:path"
10
+ import { promisify } from "node:util"
11
+
12
+ import { kriyaHome } from "../../paths.js"
13
+ import { manifestLicenceProblems } from "./licences.js"
14
+ import { fileSha256, RuntimeError } from "./manifest.js"
15
+
16
+ const exec = promisify(execFile)
17
+ const GB = 1e9
18
+
19
+ export const platformId = () => `${process.platform}-${process.arch}`
20
+ export const mediaRoot = (home = kriyaHome()) => join(home, "media")
21
+
22
+ /** A child's environment, built from scratch: nothing of Kriya's is inherited (ES-23). */
23
+ export function childEnv(home = kriyaHome(), env = process.env) {
24
+ const root = mediaRoot(home)
25
+ return { PATH: env.PATH, HOME: env.HOME, TMPDIR: env.TMPDIR, UV_CACHE_DIR: join(root, ".downloads", "uv"), UV_PYTHON_INSTALL_DIR: join(root, ".python"), UV_NO_CONFIG: "1" }
26
+ }
27
+
28
+ export const runChild = (home) => async (command, args) => (await exec(command, args, { env: childEnv(home), maxBuffer: 64 * 1024 * 1024 })).stdout
29
+
30
+ const freeBytes = (dir) => {
31
+ const { bavail, bsize } = statfsSync(dir)
32
+ return Number(bavail) * Number(bsize)
33
+ }
34
+
35
+ const sizeOf = (path) => (existsSync(path) ? statSync(path).size : 0)
36
+ const textHash = (text) => createHash("sha256").update(text).digest("hex")
37
+
38
+ async function fetchFrom(artifact, offset) {
39
+ const stopped = () => new RuntimeError(`The download of ${artifact.id} stopped. Run kriya edit setup again to resume.`)
40
+ let response
41
+ try {
42
+ response = await fetch(artifact.url, { headers: offset > 0 ? { Range: `bytes=${offset}-` } : {} })
43
+ } catch {
44
+ throw stopped()
45
+ }
46
+ if (!response.ok) throw new RuntimeError(`The download of ${artifact.id} failed: its host answered ${response.status}.`)
47
+ return { response, stopped }
48
+ }
49
+
50
+ /** Downloads to `part`, resuming what's there. The hash decides; a wrong file is deleted. */
51
+ async function download(artifact, part) {
52
+ let offset = sizeOf(part)
53
+ if (offset > artifact.bytes) {
54
+ rmSync(part)
55
+ offset = 0
56
+ }
57
+ if (offset < artifact.bytes) {
58
+ const { response, stopped } = await fetchFrom(artifact, offset)
59
+ // A host that ignores Range sends the whole file: start over
60
+ const resumed = response.status === 206
61
+ let written = resumed ? offset : 0
62
+ const out = createWriteStream(part, { flags: resumed ? "a" : "w" })
63
+ let tooLong = false
64
+ let cut = false
65
+ try {
66
+ for await (const chunk of response.body) {
67
+ written += chunk.length
68
+ if (written > artifact.bytes) {
69
+ tooLong = true
70
+ break
71
+ }
72
+ if (!out.write(chunk)) await once(out, "drain")
73
+ }
74
+ } catch {
75
+ cut = true
76
+ }
77
+ out.end()
78
+ await once(out, "close")
79
+ if (tooLong) {
80
+ rmSync(part)
81
+ throw new RuntimeError(`The download of ${artifact.id} is larger than the manifest says, so it was deleted.`)
82
+ }
83
+ if (cut) throw stopped()
84
+ }
85
+ if ((await fileSha256(part)) !== artifact.sha256) {
86
+ rmSync(part)
87
+ throw new RuntimeError(`The download of ${artifact.id} doesn't match its hash, so it was deleted. Nothing was installed.`)
88
+ }
89
+ }
90
+
91
+ async function placeArtifact(artifact, root, dir, home, say) {
92
+ say(`Downloading ${artifact.id} ${artifact.version} (${(artifact.bytes / 1e6).toFixed(0)} MB)`)
93
+ const part = join(root, ".downloads", `${artifact.sha256}.part`)
94
+ await download(artifact, part)
95
+ const target = join(dir, artifact.id)
96
+ mkdirSync(target, { recursive: true })
97
+ if (artifact.unpack === "zip") await runChild(home)("unzip", ["-q", "-o", part, "-d", target])
98
+ else cpSync(part, join(target, artifact.entry))
99
+ rmSync(part)
100
+ }
101
+
102
+ async function placePython(python, dir, run, say) {
103
+ say(`Installing the ${python.id} environment (Python ${python.version}, ${python.packages.length} packages)`)
104
+ const lock = join(dir, `${python.id}.lock`)
105
+ writeFileSync(lock, python.requirements)
106
+ const venv = join(dir, "python")
107
+ const interpreter = join(venv, "bin", "python")
108
+ await run("uv", ["venv", "--python", python.version, venv])
109
+ await run("uv", ["pip", "install", "--python", interpreter, "--require-hashes", "--only-binary", ":all:", "--index-url", "https://pypi.org/simple", "-r", lock])
110
+ await run(interpreter, ["-c", `import ${python.check}`])
111
+ }
112
+
113
+ const pointerFile = (root) => join(root, "current.json")
114
+
115
+ function readPointer(root) {
116
+ try {
117
+ return JSON.parse(readFileSync(pointerFile(root), "utf8"))
118
+ } catch {
119
+ return { current: null, previous: null }
120
+ }
121
+ }
122
+
123
+ function writePointer(root, pointer) {
124
+ const file = pointerFile(root)
125
+ writeFileSync(`${file}.new`, JSON.stringify(pointer))
126
+ renameSync(`${file}.new`, file)
127
+ }
128
+
129
+ const complete = (dir) => existsSync(join(dir, ".complete"))
130
+
131
+ /** The installed runtime in use, or null. */
132
+ export function activeRuntime(home = kriyaHome()) {
133
+ const root = mediaRoot(home)
134
+ const { current } = readPointer(root)
135
+ if (!current || !complete(join(root, current))) return null
136
+ const dir = join(root, current)
137
+ return { version: current, dir, manifest: JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8")) }
138
+ }
139
+
140
+ /** Swaps to the version used before. Both stay on disk, so it can be undone the same way. */
141
+ export function rollback(home = kriyaHome()) {
142
+ const root = mediaRoot(home)
143
+ const { current, previous } = readPointer(root)
144
+ if (!previous || !complete(join(root, previous))) throw new RuntimeError("There is nothing to roll back to.")
145
+ writePointer(root, { current: previous, previous: current })
146
+ return activeRuntime(home)
147
+ }
148
+
149
+ function use(root, version) {
150
+ const { current } = readPointer(root)
151
+ if (current !== version) writePointer(root, { current: version, previous: current })
152
+ }
153
+
154
+ /**
155
+ * @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]
157
+ */
158
+ export async function install({ text, data }, { home = kriyaHome(), platform = platformId(), run = runChild(home), free = freeBytes, say = () => {} } = {}) {
159
+ const spec = data.platforms[platform]
160
+ if (!spec) throw new RuntimeError(`This runtime isn't available for this computer (${platform}) yet.`)
161
+ refuseLicences(data)
162
+ const root = mediaRoot(home)
163
+ const dir = join(root, data.version)
164
+ mkdirSync(join(root, ".downloads"), { recursive: true })
165
+
166
+ const hash = textHash(text)
167
+ if (complete(dir) && readFileSync(join(dir, ".complete"), "utf8") === hash) {
168
+ use(root, data.version)
169
+ say(`Media Runtime ${data.version} is already installed.`)
170
+ return activeRuntime(home)
171
+ }
172
+
173
+ try {
174
+ await run("uv", ["--version"])
175
+ } catch {
176
+ throw new RuntimeError(`uv isn't installed: ${spec.system.find((tool) => tool.id === "uv")?.fix ?? "install uv"}.`)
177
+ }
178
+ // An archive and its unpacked copy exist at once, and unpack to about twice its size
179
+ const needed = spec.artifacts.reduce((sum, artifact) => sum + artifact.bytes * 3, spec.python.estimateBytes)
180
+ const available = free(dirname(dir))
181
+ if (available < needed) throw new RuntimeError(`This needs about ${(needed / GB).toFixed(1)} GB free, and there are ${(available / GB).toFixed(1)} GB.`)
182
+
183
+ rmSync(dir, { recursive: true, force: true })
184
+ mkdirSync(dir, { recursive: true })
185
+ try {
186
+ for (const artifact of spec.artifacts) await placeArtifact(artifact, root, dir, home, say)
187
+ await placePython(spec.python, dir, run, say)
188
+ writeFileSync(join(dir, "manifest.json"), text)
189
+ writeFileSync(join(dir, ".complete"), hash)
190
+ // The environment no longer needs it, and it's as big as the environment
191
+ rmSync(childEnv(home).UV_CACHE_DIR, { recursive: true, force: true })
192
+ } catch (error) {
193
+ rmSync(dir, { recursive: true, force: true })
194
+ throw error
195
+ }
196
+ use(root, data.version)
197
+ say(`Media Runtime ${data.version} is ready.`)
198
+ return activeRuntime(home)
199
+ }
200
+
201
+ // The licence gate (ET-LIC-01) before anything is downloaded
202
+ function refuseLicences(data) {
203
+ const problems = manifestLicenceProblems(data)
204
+ if (problems.length) throw new RuntimeError(`This runtime has an item outside Kriya's licence table, so nothing was installed: ${problems[0].item}, ${problems[0].problem}.`)
205
+ }
206
+
207
+ /**
208
+ * Installs one capability pack (CAPABILITY_PACKS) into the runtime in use, from the
209
+ * same signed manifest: its files go to <version>/packs/<id>/, `.complete` last. The
210
+ * core is never touched; a failure removes only the pack's own folder.
211
+ * @param {{ text: string, data: object }} opened from openManifest
212
+ */
213
+ export async function installPack({ text, data }, id, { home = kriyaHome(), platform = platformId(), free = freeBytes, say = () => {} } = {}) {
214
+ const runtime = activeRuntime(home)
215
+ if (!runtime) throw new RuntimeError("Install the Media Runtime first: kriya edit setup.")
216
+ if (runtime.version !== data.version) throw new RuntimeError(`Kriya now serves Media Runtime ${data.version}; run kriya edit setup first, then add the pack.`)
217
+ const pack = data.platforms[platform]?.packs?.[id]
218
+ if (!pack) throw new RuntimeError(`Media Runtime ${data.version} doesn't offer ${id} for this computer (${platform}).`)
219
+ refuseLicences(data)
220
+ const root = mediaRoot(home)
221
+ const dir = join(runtime.dir, "packs", id)
222
+ const hash = textHash(`${textHash(text)}:${id}`)
223
+ if (complete(dir) && readFileSync(join(dir, ".complete"), "utf8") === hash) {
224
+ say(`The ${id} pack is already installed.`)
225
+ return dir
226
+ }
227
+ const needed = pack.artifacts.reduce((sum, artifact) => sum + artifact.bytes * 3, 0)
228
+ const available = free(dirname(dir))
229
+ if (available < needed) throw new RuntimeError(`This pack needs about ${(needed / GB).toFixed(1)} GB free, and there are ${(available / GB).toFixed(1)} GB.`)
230
+ rmSync(dir, { recursive: true, force: true })
231
+ mkdirSync(join(root, ".downloads"), { recursive: true })
232
+ mkdirSync(dir, { recursive: true })
233
+ try {
234
+ for (const artifact of pack.artifacts) await placeArtifact(artifact, root, dir, home, say)
235
+ writeFileSync(join(dir, ".complete"), hash)
236
+ } catch (error) {
237
+ rmSync(dir, { recursive: true, force: true })
238
+ throw error
239
+ }
240
+ say(`The ${id} pack is ready.`)
241
+ return dir
242
+ }
243
+
244
+ /** Removes one pack from the runtime in use; the core and other packs stay. */
245
+ export function removePack(id, { home = kriyaHome() } = {}) {
246
+ if (!/^pack-[a-z0-9-]+$/.test(id)) throw new RuntimeError("That isn't a pack's name.")
247
+ const runtime = activeRuntime(home)
248
+ const dir = runtime && join(runtime.dir, "packs", id)
249
+ if (!dir || !existsSync(dir)) throw new RuntimeError(`The ${id} pack isn't installed.`)
250
+ rmSync(dir, { recursive: true, force: true })
251
+ return dir
252
+ }
package/src/failure.js ADDED
@@ -0,0 +1,69 @@
1
+ // Kriya loop v2 (docs/kriya-harness/KRIYA_LOOP_V2.md in the Kriya
2
+ // repository): a failed check's output, classified by code and cut to its
3
+ // signal. The class is a fixed list matched by patterns, never a model's
4
+ // opinion; the excerpt keeps the lines that name the failure (and one line
5
+ // around each) instead of only the tail.
6
+
7
+ // Most specific first: a timeout hides everything after it, a missing tool
8
+ // isn't the code's fault, and code that doesn't parse can't fail a test
9
+ export const CLASSES = [
10
+ ["environment", [/command not found/i, /\bENOENT\b/, /\bEACCES\b/, /\bECONNREFUSED\b/, /npm (ERR!|error) missing script/i, /No module named /, /Cannot find package /]],
11
+ [
12
+ "syntax",
13
+ [/\bSyntaxError\b/, /\bIndentationError\b/, /\berror TS1\d{3}\b/, /\bsyntax error\b/i, /\bParseError\b/, /Unexpected token/, /error: expected /, /error\[E0(?:0|1)\d\d\]/],
14
+ ],
15
+ ["type", [/\berror TS[2-9]\d{3}\b/, /\bTypeError\b/, /mismatched types/, /error\[E0308\]/, /cannot use .+ as .+ value/, /incompatible type/i, /\bNameError\b/, /\bReferenceError\b/]],
16
+ [
17
+ "assertion",
18
+ [/\bAssertionError\b/, /\bassert(ion)?\b.*fail/i, /^not ok \d+/m, /^--- FAIL/m, /^\s*E\s+assert /m, /\bExpected\b.*\b(Received|but got|to (be|equal))\b/i, /^\s*(✗|✕|×|FAIL)\s/m, /\b\d+ (failed|failing)\b/],
19
+ ],
20
+ ]
21
+
22
+ // The order a fix can move through: lower is further from passing
23
+ export const RANK = { timeout: 0, environment: 0, syntax: 1, type: 2, unknown: 2, assertion: 3, "tests changed": 3, silenced: 3, "invariant broken": 3, acceptance: 3, "no reproduction": 3, "invariant violated": 3, "regression hazard": 3, "no negative test": 3, "premortem open": 3, pass: 4 }
24
+
25
+ const EXCERPT = 2500
26
+
27
+ /**
28
+ * @param {{ output?: string, exitCode?: number | null, timedOut?: boolean }} run
29
+ * @returns {{ kind: string, excerpt: string }}
30
+ */
31
+ export function classify({ output = "", exitCode, timedOut } = {}) {
32
+ const kind = timedOut ? "timeout" : exitCode === 127 || exitCode === 126 ? "environment" : (CLASSES.find(([, res]) => res.some((re) => re.test(output)))?.[0] ?? "unknown")
33
+ return { kind, excerpt: excerpt(output) }
34
+ }
35
+
36
+ const ANY = CLASSES.flatMap(([, res]) => res)
37
+ // Locations (file:line) are signal too: they say where to look
38
+ const LOCATION = /[\w./-]+\.\w+:\d+/
39
+ const LIBRARY = /node_modules|node:internal|site-packages/
40
+
41
+ /** The lines that name a failure, with one line of context each, in order and deduplicated. */
42
+ export function excerpt(output, limit = EXCERPT) {
43
+ const lines = output.split("\n")
44
+ const keep = new Set()
45
+ lines.forEach((line, i) => {
46
+ if (ANY.some((re) => re.test(line)) || (LOCATION.test(line) && !LIBRARY.test(line))) for (const j of [i - 1, i, i + 1]) if (j >= 0 && j < lines.length) keep.add(j)
47
+ })
48
+ // Nothing recognisable: the end, where test runners report
49
+ if (!keep.size) return output.length <= limit ? output : `… (${output.length - limit} earlier characters left out)\n${output.slice(-limit)}`
50
+ const picked = []
51
+ let last = -2
52
+ const seen = new Set()
53
+ for (const i of [...keep].sort((a, b) => a - b)) {
54
+ const line = lines[i].trimEnd()
55
+ if (seen.has(line) && line) continue
56
+ seen.add(line)
57
+ if (i !== last + 1 && picked.length) picked.push("…")
58
+ picked.push(line)
59
+ last = i
60
+ }
61
+ const text = picked.join("\n")
62
+ return text.length <= limit ? text : `${text.slice(0, limit)}\n… (cut)`
63
+ }
64
+
65
+ /** What a repeated failure is recognised by: the command, the class and its first named line, without numbers that change between runs. */
66
+ export function signature(command, { kind, excerpt: text }) {
67
+ const first = text.split("\n").find((line) => ANY.some((re) => re.test(line))) ?? ""
68
+ return `${command}\0${kind}\0${first.replace(/\d+/g, "#").replace(/\s+/g, " ").trim().slice(0, 160)}`
69
+ }
@@ -0,0 +1,213 @@
1
+ import { createServer } from "node:http"
2
+ import { Readable } from "node:stream"
3
+ import { pipeline } from "node:stream/promises"
4
+ import { setTimeout as sleep } from "node:timers/promises"
5
+ import { gzipSync } from "node:zlib"
6
+
7
+ import { BASE_PATH } from "./api.js"
8
+
9
+ // The local relay between DSH and the Kriya gateway (2026-11-04, owner
10
+ // decision in chat: "Encode bodies (I approve)"). Kriya's host (Render,
11
+ // behind Cloudflare) runs a web application firewall that reads request
12
+ // bodies, and Render offers no setting to exclude a path. An agent's
13
+ // conversation is full of what such rules match (shell commands, HTML,
14
+ // test code, paths): on a real long task the host answered a 403 "Blocked"
15
+ // page mid-turn, DSH read it as "API key is invalid", and every later turn
16
+ // re-sent the same history and was blocked again. Harness requests are
17
+ // authenticated by the device token, and their content is model input the
18
+ // server never executes; the gateway validates every decoded body with the
19
+ // same schema as before.
20
+ //
21
+ // When Kriya says it reads them (GET /models `bodyEncodings`), JSON bodies
22
+ // go as gzip then base64 (`x-kriya-body: gzip+base64`); otherwise they go
23
+ // unchanged. A firewall block page is turned into a plain 400 that says
24
+ // what happened, never a 401/403 (which DSH reports as a bad API key).
25
+ //
26
+ // Loopback only, on a random port; adds no credential (DSH sends the device
27
+ // token itself); forwards only under the harness API's path to the
28
+ // signed-in Kriya; streams answers back unchanged; stops the upstream
29
+ // request when DSH hangs up.
30
+
31
+ export const BODY_ENCODING = "gzip+base64"
32
+ // Larger requests are refused locally (a 1M-token history is about 4 MB of JSON)
33
+ export const MAX_BODY = 64 * 1024 * 1024
34
+ // While Kriya doesn't decode encoded bodies, how often it is asked again (a deploy after launch)
35
+ export const RECHECK_MS = 60_000
36
+ // Before a blocked request is sent once more, unencoded
37
+ export const RETRY_MS = 2_000
38
+ // How long one request waits out a network outage. Under DSH's 5-minute stream timeout, and DSH
39
+ // retries a 502 five times, so a long task survives about 20 minutes offline: its own retries alone
40
+ // run out in about 15 seconds. Connections only: nothing below can have reached Kriya
41
+ export const OUTAGE_MS = 4 * 60_000
42
+ const OUTAGE_WAIT_MS = 15_000
43
+ const NO_CONNECTION = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH", "ENETDOWN", "UND_ERR_CONNECT_TIMEOUT"])
44
+ // A pooled connection the host had closed. The request may have reached Kriya, so once only
45
+ const DEAD_SOCKET = new Set(["ECONNRESET", "EPIPE", "UND_ERR_SOCKET"])
46
+ const DROP_REQUEST = new Set(["host", "connection", "keep-alive", "content-length", "transfer-encoding", "accept-encoding", "expect", "upgrade", "proxy-connection"])
47
+ const DROP_RESPONSE = new Set(["connection", "keep-alive", "content-length", "transfer-encoding", "content-encoding"])
48
+
49
+ /** The host firewall's block page, as { requestId }, or null for anything else */
50
+ export function firewallBlock(status, contentType, text) {
51
+ if (status !== 403 || !/text\/html/i.test(contentType ?? "")) return null
52
+ if (!/web application firewall/i.test(text)) return null
53
+ return { requestId: /Request ID:\s*(?:<[^>]+>\s*)*([A-Za-z0-9-]{6,64})/i.exec(text)?.[1] ?? null }
54
+ }
55
+
56
+ /** What DSH is told about a block: a 400 (shown, not retried) */
57
+ export function blockedAnswer(requestId) {
58
+ const message =
59
+ `Kriya's host firewall blocked this request${requestId ? ` (request ID ${requestId})` : ""}. ` +
60
+ "Your sign-in is fine. Update Kriya Harness and restart it; if it happens again, give the Kriya owner the request ID."
61
+ return JSON.stringify({ error: { message, type: "blocked_by_host", code: "blocked_by_host" } })
62
+ }
63
+
64
+ /** A JSON body in the form the gateway decodes */
65
+ export const encodeBody = (buffer) => Buffer.from(gzipSync(buffer).toString("base64"), "ascii")
66
+
67
+ async function readAll(req) {
68
+ const chunks = []
69
+ let size = 0
70
+ for await (const chunk of req) {
71
+ size += chunk.length
72
+ if (size > MAX_BODY) return null
73
+ chunks.push(chunk)
74
+ }
75
+ return Buffer.concat(chunks)
76
+ }
77
+
78
+ /**
79
+ * Starts the relay in front of `target` (the signed-in Kriya's address).
80
+ * `encode`: whether Kriya decodes encoded bodies, as known at launch.
81
+ * `checkSupport` asks Kriya again (GET /models): while encoding is off it
82
+ * is asked at most every RECHECK_MS, and at once after a firewall block,
83
+ * so a Kriya deployed after launch is picked up without a restart.
84
+ * A request the firewall blocked never reached Kriya, so it is sent once
85
+ * more: encoded if Kriya now decodes it, else after RETRY_MS. Only then is
86
+ * the block reported.
87
+ * @param {{ target: string, encode: boolean, checkSupport?: () => Promise<boolean>, fetchImpl?: typeof fetch, log?: (text: string) => void, now?: () => number, retryMs?: number }} options
88
+ * @returns {Promise<{ url: string, close: () => Promise<void>, encoding: () => boolean }>} url stands in for device.url inside DSH
89
+ */
90
+ export async function startGatewayProxy({ target, encode, checkSupport, fetchImpl = fetch, log = () => {}, now = Date.now, retryMs = RETRY_MS, outageMs = OUTAGE_MS, outageWaitMs = OUTAGE_WAIT_MS }) {
91
+ const origin = new URL(target).origin
92
+ const support = { on: Boolean(encode), checked: now(), pending: null }
93
+ // One question at a time; a failed question changes nothing
94
+ const recheck = () => {
95
+ if (support.on || !checkSupport) return Promise.resolve(support.on)
96
+ support.pending ??= checkSupport()
97
+ .then((on) => {
98
+ if (on && !support.on) log("Kriya now decodes encoded request bodies; using them")
99
+ support.on = Boolean(on)
100
+ })
101
+ .catch(() => {})
102
+ .finally(() => {
103
+ support.checked = now()
104
+ support.pending = null
105
+ })
106
+ return support.pending.then(() => support.on)
107
+ }
108
+ const server = createServer(async (req, res) => {
109
+ const upstream = new AbortController()
110
+ res.on("close", () => upstream.abort())
111
+ const reply = (status, body) => {
112
+ if (res.headersSent) return res.destroy()
113
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" })
114
+ res.end(body)
115
+ }
116
+ const error = (status, message) => reply(status, JSON.stringify({ error: { message } }))
117
+ try {
118
+ const path = new URL(req.url ?? "/", "http://relay").pathname
119
+ if (path !== BASE_PATH && !path.startsWith(`${BASE_PATH}/`)) return error(404, "Not a Kriya Harness route.")
120
+ const body = req.method === "GET" || req.method === "HEAD" ? undefined : await readAll(req)
121
+ if (body === null) return error(413, "This request is larger than Kriya Harness sends (64 MB).")
122
+ const headers = {}
123
+ for (const [name, value] of Object.entries(req.headers)) if (!DROP_REQUEST.has(name) && value !== undefined) headers[name] = Array.isArray(value) ? value.join(", ") : value
124
+ const plain = body?.length ? body : undefined
125
+ const encodable = Boolean(plain) && /^application\/json\b/i.test(headers["content-type"] ?? "")
126
+ if (encodable && !support.on && now() - support.checked >= RECHECK_MS) await recheck()
127
+ const once = (encoded) => {
128
+ const h = { ...headers }
129
+ let sent = plain
130
+ if (encoded) {
131
+ sent = encodeBody(plain)
132
+ h["content-type"] = "text/plain; charset=us-ascii"
133
+ h["x-kriya-body"] = BODY_ENCODING
134
+ }
135
+ return fetchImpl(`${origin}${req.url}`, { method: req.method, headers: h, body: sent, signal: upstream.signal, redirect: "manual" })
136
+ }
137
+ /** One request through an outage: waits while nothing can connect, and tries a dead pooled connection once more */
138
+ const send = async (encoded) => {
139
+ const began = now()
140
+ let waiting = false
141
+ let retried = false
142
+ for (let wait = Math.min(1000, outageWaitMs); ; wait = Math.min(wait * 2, outageWaitMs)) {
143
+ try {
144
+ const answer = await once(encoded)
145
+ if (waiting) log("relay: Kriya is reachable again")
146
+ return answer
147
+ } catch (e) {
148
+ const code = e?.cause?.code
149
+ if (upstream.signal.aborted) throw e
150
+ if (DEAD_SOCKET.has(code) && !retried) {
151
+ retried = true
152
+ continue
153
+ }
154
+ if (!NO_CONNECTION.has(code) || now() - began >= outageMs) throw e
155
+ if (!waiting) log(`relay: can't reach Kriya (${code}); waiting for the network`)
156
+ waiting = true
157
+ await sleep(wait, undefined, { signal: upstream.signal })
158
+ }
159
+ }
160
+ }
161
+ /** The firewall's block, or null; a 403 web page's body is read here (it is never passed on) */
162
+ const blockOf = async (answer) => {
163
+ const type = answer.headers.get("content-type") ?? ""
164
+ if (answer.status !== 403 || !/text\/html/i.test(type)) return null
165
+ return firewallBlock(answer.status, type, await answer.text().catch(() => "")) ?? null
166
+ }
167
+ let encoded = encodable && support.on
168
+ let answer = await send(encoded)
169
+ let block = await blockOf(answer)
170
+ if (block) {
171
+ log(`the host firewall blocked ${req.method} ${path}${encoded ? " (encoded)" : ""}${block.requestId ? ` (request ID ${block.requestId})` : ""}; sending it once more`)
172
+ // It never reached Kriya, so sending it again repeats nothing
173
+ if (encodable && !encoded && (await recheck())) encoded = true
174
+ else await new Promise((done) => setTimeout(done, retryMs))
175
+ answer = await send(encoded)
176
+ block = await blockOf(answer)
177
+ if (block) {
178
+ log(`the host firewall blocked ${req.method} ${path} again${block.requestId ? ` (request ID ${block.requestId})` : ""}`)
179
+ return reply(400, blockedAnswer(block.requestId))
180
+ }
181
+ }
182
+ if (answer.status === 403 && /text\/html/i.test(answer.headers.get("content-type") ?? ""))
183
+ return error(502, "Kriya answered with a web page instead of an answer; try again in a minute.")
184
+ const out = {}
185
+ answer.headers.forEach((value, name) => {
186
+ if (!DROP_RESPONSE.has(name)) out[name] = value
187
+ })
188
+ res.writeHead(answer.status, out)
189
+ if (!answer.body) return res.end()
190
+ await pipeline(Readable.fromWeb(answer.body), res)
191
+ } catch (e) {
192
+ // DSH hung up: before an answer it's an abort, during one the stream closes early
193
+ if (e?.name === "AbortError" || e?.code === "ERR_STREAM_PREMATURE_CLOSE") return
194
+ // The code only: a fetch TypeError's message can quote a header. DSH retries on the 502 below
195
+ log(`relay: connection to Kriya dropped (${e?.cause?.code ?? e?.name ?? "error"}); retrying`)
196
+ error(502, `Couldn't reach Kriya (${e?.cause?.code ?? e?.name ?? "network error"}).`)
197
+ }
198
+ })
199
+ await new Promise((done, fail) => {
200
+ server.once("error", fail)
201
+ server.listen(0, "127.0.0.1", done)
202
+ })
203
+ const { port } = /** @type {import("node:net").AddressInfo} */ (server.address())
204
+ return {
205
+ url: `http://127.0.0.1:${port}`,
206
+ encoding: () => support.on,
207
+ close: () =>
208
+ new Promise((done) => {
209
+ server.closeAllConnections?.()
210
+ server.close(() => done())
211
+ }),
212
+ }
213
+ }