@kriya-ai/harness 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
package/src/daemon.js ADDED
@@ -0,0 +1,503 @@
1
+ import { spawn } from "node:child_process"
2
+ import { createHash, randomUUID } from "node:crypto"
3
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"
4
+ import { homedir, tmpdir } from "node:os"
5
+ import { basename, join, sep } from "node:path"
6
+ import { gzipSync } from "node:zlib"
7
+
8
+ import { BASE_PATH, call, KriyaError, models } from "./api.js"
9
+ import { doctor } from "./doctor.js"
10
+ import { CLIENT_VERSION, kriyaHome } from "./paths.js"
11
+ import { confirmRule, dismissRule, listRules } from "./rules.js"
12
+
13
+ // `kriya daemon` (the Control Center, CONTROL_CENTER.md in the Kriya
14
+ // repository): this computer listens for actions the person queues in
15
+ // Kriya (/harness, or the phone) and runs them with the same routines as
16
+ // the terminal. What it accepts is decided here, on the computer:
17
+ // - only the folders the person offered (the one it started in and each
18
+ // --folder), never a path from Kriya;
19
+ // - only typed actions (a task, a health check, a rule decision, handoff,
20
+ // pull, serve), never a command;
21
+ // - Full access and serving only with --allow-full-access / --allow-serve;
22
+ // - a task runs `kriya run` exactly as typed in a terminal would, so Ask
23
+ // mode's approvals still go to Kriya and the person answers them there.
24
+
25
+ export const POLL_WAIT_S = 25
26
+ export const MAX_RUNNING = 2
27
+ const OUTPUT_TAIL = 4000
28
+ const REHELLO_MS = 5 * 60_000
29
+ const BACKOFF_MS = [1_000, 2_000, 5_000, 10_000, 30_000]
30
+
31
+ /** A folder's id: the first 16 hex of the sha256 of its real path */
32
+ export const projectId = (path) => createHash("sha256").update(path).digest("hex").slice(0, 16)
33
+
34
+ /**
35
+ * The folders this computer offers: real, existing directories, never the
36
+ * home folder or a drive root, at most 50.
37
+ * @param {string[]} folders
38
+ */
39
+ export function offeredProjects(folders, home = homedir()) {
40
+ const out = []
41
+ for (const raw of folders) {
42
+ let path
43
+ try {
44
+ path = realpathSync(raw)
45
+ if (!statSync(path).isDirectory()) continue
46
+ } catch {
47
+ continue
48
+ }
49
+ if (path === realpathSync(home) || path === sep || /^[A-Za-z]:\\?$/.test(path)) continue
50
+ if (out.some((p) => p.path === path)) continue
51
+ out.push({
52
+ id: projectId(path),
53
+ name: basename(path).slice(0, 80) || path,
54
+ path,
55
+ shown: (path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path).slice(0, 300),
56
+ git: existsSync(join(path, ".git")),
57
+ })
58
+ if (out.length >= 50) break
59
+ }
60
+ return out
61
+ }
62
+
63
+ /** Each offered folder's loop rules: proposed ones by number, then confirmed */
64
+ export function projectRules(projects) {
65
+ const rules = []
66
+ for (const p of projects) {
67
+ try {
68
+ const { proposed, confirmed } = listRules(p.path)
69
+ proposed.forEach((text, i) => rules.push({ project: p.id, n: i + 1, text: text.slice(0, 400), status: "proposed" }))
70
+ confirmed.forEach((text, i) => rules.push({ project: p.id, n: i + 1, text: text.slice(0, 400), status: "confirmed" }))
71
+ } catch {
72
+ // No rules file: nothing to list
73
+ }
74
+ }
75
+ return rules.slice(0, 200)
76
+ }
77
+
78
+ /** The modes and switches of a task, as `kriya run` flags */
79
+ export function runArgs(payload) {
80
+ const s = payload.switches ?? {}
81
+ return [
82
+ "run",
83
+ "--mode",
84
+ payload.mode,
85
+ ...(s.loopV2 ? ["--loop-v2"] : []),
86
+ ...(s.budget === false ? ["--no-budget"] : []),
87
+ ...(s.anchor ? ["--anchor"] : []),
88
+ ...(s.browser === false ? ["--no-browser-tools"] : []),
89
+ payload.prompt,
90
+ ]
91
+ }
92
+
93
+ // The harness switches a flow may set (KU-ADR-16: nothing protected has a name)
94
+ const PROFILE_ENV = /^KRIYA_(LOOP|LOOP_V2|LOOP_GUARD|STRICT_LOOP|DEFENSIVE|RECON|JIT_TOOLS|BUDGET|ANCHOR|MINIMAL|MAX_STEPS|TURN_MINUTES|MAX_REPEATS)$/
95
+ const FLOW_REPORT_MS = 3_000
96
+
97
+ /**
98
+ * What a flow from Kriya adds to `kriya run`: its plan in a file the loop
99
+ * saves as written, a file the loop reports into, and its harness settings,
100
+ * only the known switches, each a short value. Refuses anything else, as the
101
+ * server does, so a tampered action changes nothing protected.
102
+ */
103
+ export function flowEnv(payload, dir) {
104
+ const env = {}
105
+ if (payload.profile) {
106
+ for (const [name, value] of Object.entries(payload.profile.env ?? {}))
107
+ if (PROFILE_ENV.test(name) && /^(on|off|[0-9]{1,3})$/.test(String(value))) env[name] = String(value)
108
+ }
109
+ if (!payload.plan) return env
110
+ const seed = join(dir, "plan.json")
111
+ writeFileSync(seed, JSON.stringify(payload.plan))
112
+ return { ...env, KRIYA_SEED_PLAN: seed, KRIYA_PROGRESS_FILE: join(dir, "progress.json") }
113
+ }
114
+
115
+ const readProgressFile = (file) => {
116
+ try {
117
+ return JSON.parse(readFileSync(file, "utf8"))
118
+ } catch {
119
+ return null
120
+ }
121
+ }
122
+
123
+ const tail = (text) => (text.length > OUTPUT_TAIL ? `…${text.slice(-OUTPUT_TAIL)}` : text)
124
+ const MODES = new Set(["ask", "auto", "read", "plan", "full"])
125
+
126
+ /** Sends to Kriya, with bodies past the host's firewall when Kriya decodes them (as the relay does) */
127
+ export async function deviceSender(device) {
128
+ let encode = false
129
+ try {
130
+ encode = ((await models(device.url, device.token)).bodyEncodings ?? []).includes("gzip+base64")
131
+ } catch {
132
+ // Plain JSON until the next sender asks
133
+ }
134
+ return (method, path, body) =>
135
+ encode && body !== undefined
136
+ ? call(device.url, method, path, {
137
+ token: device.token,
138
+ raw: true,
139
+ headers: { "Content-Type": "text/plain; charset=us-ascii", "x-kriya-body": "gzip+base64" },
140
+ bodyText: gzipSync(Buffer.from(JSON.stringify(body))).toString("base64"),
141
+ }).then(async (r) => (r.status === 204 ? null : r.json()))
142
+ : call(device.url, method, path, { token: device.token, ...(body !== undefined && { body }) })
143
+ }
144
+
145
+ /* The running `kriya daemon` command's pid: Remote Control leaves listening to it */
146
+ export const daemonPidFile = () => join(kriyaHome(), "daemon.pid")
147
+
148
+ export function externalDaemon(file = daemonPidFile()) {
149
+ try {
150
+ process.kill(Number(readFileSync(file, "utf8")), 0)
151
+ return true
152
+ } catch {
153
+ return false
154
+ }
155
+ }
156
+
157
+ /**
158
+ * The daemon: hello, then a long poll for actions, each run on this
159
+ * computer and reported. Stops when `signal` aborts (Ctrl-C).
160
+ * @param {{
161
+ * device: { url: string, token: string },
162
+ * folders: string[],
163
+ * allowFullAccess?: boolean,
164
+ * allowServe?: boolean,
165
+ * allowEdit?: boolean,
166
+ * editHost?: { hand: (job: object) => Promise<any>, cancel: (body: object) => Promise<{ known: boolean }> },
167
+ * env?: Record<string, string | undefined>,
168
+ * signal?: AbortSignal,
169
+ * log?: (line: string) => void,
170
+ * kriya?: { bin: string, node: string },
171
+ * once?: boolean,
172
+ * }} options once: handle one poll and return (tests)
173
+ */
174
+ export async function runDaemon(options) {
175
+ const { device, signal, log = (line) => process.stdout.write(`${line}\n`) } = options
176
+ const kriya = options.kriya ?? { bin: join(import.meta.dirname, "..", "bin", "kriya.js"), node: process.execPath }
177
+ let projects = offeredProjects(options.folders)
178
+ const capabilities = { fullAccess: Boolean(options.allowFullAccess), serve: Boolean(options.allowServe), handoff: true }
179
+ const send = await deviceSender(device)
180
+
181
+ const running = new Map() // dispatch id → { child, canceled }
182
+ let serving = null // { child, project, id }
183
+ let helloAt = 0
184
+
185
+ // Editing (track E). Edits never enter `running`, so MAX_RUNNING stays the person's
186
+ // tasks (EH-02), and the Host, detached, outlives this process (EH-05). With KRIYA_EDIT
187
+ // off none of this does anything: no request, no field, the old cancel path.
188
+ const editSwitch = (options.env ?? process.env).KRIYA_EDIT === "on"
189
+ const editing = new Set()
190
+ const canceling = new Set() // forwarded to the Host and not yet over
191
+ let allowEdit = Boolean(options.allowEdit)
192
+ let editAdvertised = false
193
+ const editHost = options.editHost ?? {
194
+ async hand(job) {
195
+ const { ensureHost, hostCall } = await import("./edit/host/client.js")
196
+ await ensureHost()
197
+ return hostCall(kriyaHome(), "POST", "/internal/job", job)
198
+ },
199
+ async cancel(body) {
200
+ const { hostCall } = await import("./edit/host/client.js")
201
+ return hostCall(kriyaHome(), "POST", "/internal/cancel", body)
202
+ },
203
+ // After a restart the Host isn't up yet, and a watched folder needs it to be
204
+ async wake() {
205
+ const { watchedFolders } = await import("./edit/host/watch.js")
206
+ if (!watchedFolders({ home: kriyaHome() }).length) return
207
+ const { ensureHost } = await import("./edit/host/client.js")
208
+ await ensureHost()
209
+ },
210
+ }
211
+ // Strict schemas: a field only after this server said it knows editing (EH-01)
212
+ const refreshEdit = async () => {
213
+ if (editSwitch && allowEdit && !editAdvertised) {
214
+ try {
215
+ await call(device.url, "GET", "/editing/manifest", { token: device.token })
216
+ editAdvertised = true
217
+ } catch {
218
+ // Not on this Kriya yet; asked again at the next hello
219
+ }
220
+ }
221
+ if (editSwitch && allowEdit && editAdvertised) {
222
+ capabilities.edit = true
223
+ await editHost.wake?.().catch((error) => log(`kriya daemon: the Edit Host didn't start: ${error.message}`))
224
+ } else delete capabilities.edit
225
+ }
226
+
227
+ const hello = async () => {
228
+ await refreshEdit()
229
+ await send("POST", "/daemon/hello", { daemonVersion: CLIENT_VERSION, capabilities, projects: projects.map((p) => ({ id: p.id, name: p.name, path: p.shown, git: p.git })), rules: projectRules(projects) })
230
+ helloAt = Date.now()
231
+ }
232
+ // Remote Control changes folders and switches without stopping running tasks
233
+ if (options.control)
234
+ options.control.update = (next) => {
235
+ projects = offeredProjects(next.folders)
236
+ capabilities.fullAccess = Boolean(next.allowFullAccess)
237
+ capabilities.serve = Boolean(next.allowServe)
238
+ allowEdit = Boolean(next.allowEdit)
239
+ return hello().catch(() => (helloAt = 0))
240
+ }
241
+ const report = (id, status, result) => send("POST", `/dispatch/${id}`, { status, ...(result && { result }) }).catch((error) => log(`kriya daemon: couldn't report ${id.slice(0, 8)}: ${error.message}`))
242
+
243
+ const folderOf = (payload) => projects.find((p) => p.id === payload.project)
244
+
245
+ // A child kriya command in a folder; resolves with its exit code and output
246
+ const child = (id, args, cwd, extraEnv = {}) =>
247
+ new Promise((done) => {
248
+ const proc = spawn(kriya.node, [kriya.bin, ...args], { cwd, env: { ...process.env, KRIYA_DISPATCH_ID: id, ...extraEnv }, stdio: ["ignore", "pipe", "pipe"] })
249
+ let out = ""
250
+ let err = ""
251
+ proc.stdout.on("data", (d) => (out = (out + d).slice(-OUTPUT_TAIL * 2)))
252
+ proc.stderr.on("data", (d) => (err = (err + d).slice(-OUTPUT_TAIL * 2)))
253
+ running.set(id, { child: proc, canceled: false })
254
+ proc.on("error", (error) => done({ code: 1, out, err: `${err}\n${error.message}`, canceled: running.get(id)?.canceled }))
255
+ proc.on("close", (code, sig) => done({ code: code ?? (sig ? 1 : 0), out, err, canceled: running.get(id)?.canceled }))
256
+ }).finally(() => running.delete(id))
257
+
258
+ const handle = async ({ id, kind, payload }) => {
259
+ const refuse = (error) => report(id, "failed", { error })
260
+ if (kind === "doctor") {
261
+ const lines = []
262
+ await report(id, "running")
263
+ const ok = await doctor({ say: (line) => lines.push(line) }).catch((error) => (lines.push(`FAIL doctor — ${error.message}`), false))
264
+ const checks = lines.map((line) => {
265
+ const m = /^(ok|FAIL)\s+(.*?)(?: — (.*))?$/.exec(line)
266
+ return m ? { name: m[2].slice(0, 200), ok: m[1] === "ok", ...(m[3] && { fix: m[3].slice(0, 300) }) } : { name: line.slice(0, 200), ok: true }
267
+ })
268
+ return report(id, ok ? "done" : "failed", { checks })
269
+ }
270
+ if (kind === "serve_stop") {
271
+ if (serving) serving.child.kill("SIGTERM")
272
+ return report(id, "done", { output: serving ? "Stopped serving." : "Wasn't serving." })
273
+ }
274
+ const folder = folderOf(payload)
275
+ if (!folder) return refuse("That folder isn't offered by this computer any more.")
276
+ if (kind === "rule_confirm" || kind === "rule_dismiss") {
277
+ try {
278
+ const text = kind === "rule_confirm" ? confirmRule(folder.path, payload.n, payload.wording) : dismissRule(folder.path, payload.n)
279
+ await report(id, "done", { output: `${kind === "rule_confirm" ? "Confirmed" : "Dismissed"}: ${text}` })
280
+ } catch (error) {
281
+ await refuse(error.message)
282
+ }
283
+ return hello().catch(() => {})
284
+ }
285
+ if (kind === "run") {
286
+ if (!MODES.has(payload.mode) || typeof payload.prompt !== "string" || !payload.prompt.trim()) return refuse("That task isn't complete.")
287
+ if (payload.mode === "full" && !capabilities.fullAccess) return refuse("Full access from Kriya is off on this computer.")
288
+ if (running.size >= MAX_RUNNING) return refuse(`This computer is already running ${MAX_RUNNING} tasks from Kriya.`)
289
+ await report(id, "running")
290
+ log(`kriya daemon: task in ${folder.shown} (${payload.mode})`)
291
+ const flow = payload.plan || payload.profile ? mkdtempSync(join(tmpdir(), "kriya-flow-")) : null
292
+ const env = flow ? flowEnv(payload, flow) : {}
293
+ let sent = ""
294
+ const beat = () => {
295
+ const seen = env.KRIYA_PROGRESS_FILE && readProgressFile(env.KRIYA_PROGRESS_FILE)
296
+ if (!seen || JSON.stringify(seen) === sent) return seen
297
+ sent = JSON.stringify(seen)
298
+ report(id, "running", seen)
299
+ return seen
300
+ }
301
+ const reporting = env.KRIYA_PROGRESS_FILE ? setInterval(beat, FLOW_REPORT_MS) : null
302
+ const r = await child(id, runArgs(payload), folder.path, env)
303
+ clearInterval(reporting)
304
+ const progress = env.KRIYA_PROGRESS_FILE ? readProgressFile(env.KRIYA_PROGRESS_FILE) : null
305
+ if (flow) rmSync(flow, { recursive: true, force: true })
306
+ const stopped = r.canceled
307
+ // The answer on success; on failure the last error lines too (DSH writes the reason to stderr)
308
+ const errors = r.err
309
+ .split("\n")
310
+ .filter((line) => line.trim() && !/^(dsh: warning: \d+ entries did not activate|kriya-[\w-]+ \(@kriya-ai\/[\w-]+\): pending)/.test(line))
311
+ .join("\n")
312
+ const answer = r.code === 0 ? r.out.trim() || errors : [r.out.trim(), errors].filter(Boolean).join("\n\n")
313
+ return report(id, stopped ? "canceled" : r.code === 0 ? "done" : "failed", { exitCode: r.code, answer: tail(answer), ...(progress && { plan: progress.plan }) })
314
+ }
315
+ if (kind === "edit") {
316
+ if (!capabilities.edit) return report(id, "failed", { code: "not_allowed" })
317
+ await report(id, "running")
318
+ editing.add(id)
319
+ try {
320
+ await editHost.hand({ dispatch: id, folder: folder.path, job: payload.job, brief: payload.brief, effort: payload.effort, ...(payload.recipe && { recipe: payload.recipe }), ...(payload.revisionOf && { revisionOf: payload.revisionOf }), ...(payload.change && { change: payload.change }) })
321
+ log(`kriya daemon: an edit in ${folder.shown} went to the Edit Host`)
322
+ } catch (error) {
323
+ editing.delete(id)
324
+ log(`kriya daemon: the Edit Host didn't take it: ${error.message}`)
325
+ return report(id, "failed", { code: "runtime_missing" })
326
+ }
327
+ return
328
+ }
329
+ if (kind === "handoff" || kind === "pull") {
330
+ if (!folder.git) return refuse("Handoff and pull need a git repository.")
331
+ await report(id, "running")
332
+ const args = kind === "handoff" ? ["handoff", ...(payload.note ? [payload.note] : [])] : ["pull", ...(payload.workspace ? [payload.workspace] : [])]
333
+ const r = await child(id, args, folder.path)
334
+ const text = `${r.out}\n${r.err}`.trim()
335
+ const workspace = /\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/.exec(text)?.[1]
336
+ const branch = /\b(kriya\/pull-[\w-]+)\b/.exec(text)?.[1]
337
+ return report(id, r.code === 0 ? "done" : "failed", { exitCode: r.code, output: tail(text), ...(workspace && { workspace }), ...(branch && { branch }) })
338
+ }
339
+ if (kind === "serve_start") {
340
+ if (!capabilities.serve) return refuse("Serving from Kriya is off on this computer.")
341
+ if (serving) return refuse(`Already serving ${serving.project.name}.`)
342
+ const proc = spawn(kriya.node, [kriya.bin, "serve", folder.path], { cwd: folder.path, env: { ...process.env, KRIYA_DISPATCH_ID: id }, stdio: "ignore" })
343
+ serving = { child: proc, project: folder, id }
344
+ proc.on("close", () => {
345
+ if (serving?.child === proc) serving = null
346
+ report(id, "done", { output: `Stopped serving ${folder.name}.` })
347
+ })
348
+ log(`kriya daemon: serving ${folder.shown}`)
349
+ return report(id, "running")
350
+ }
351
+ return refuse("This computer doesn't know that action.")
352
+ }
353
+
354
+ log(`kriya daemon: listening for Kriya (${projects.length} folder${projects.length === 1 ? "" : "s"}: ${projects.map((p) => p.shown).join(", ") || "none"})`)
355
+ let failures = 0
356
+ while (!signal?.aborted) {
357
+ try {
358
+ if (Date.now() - helloAt > REHELLO_MS) await hello()
359
+ const next = await call(device.url, "GET", `/dispatch/next?wait=${options.once ? 0 : POLL_WAIT_S}`, { token: device.token, signal: AbortSignal.any([signal ?? new AbortController().signal, AbortSignal.timeout((POLL_WAIT_S + 15) * 1000)]) })
360
+ failures = 0
361
+ for (const id of next.cancel ?? []) {
362
+ // First, so cancelling an edit never reaches `kriya serve` (EH-03). After a
363
+ // restart the set is empty, so an id that's no one's goes to the Host too; the
364
+ // Host's "don't know it" closes it at once, or Kriya's poll runs hot (EH-04)
365
+ if (editSwitch && (editing.has(id) || (!running.has(id) && serving?.id !== id))) {
366
+ if (canceling.has(id)) continue
367
+ canceling.add(id)
368
+ const closed = () => {
369
+ editing.delete(id)
370
+ return report(id, "canceled", { code: "unknown" })
371
+ }
372
+ editHost
373
+ .cancel({ dispatch: id })
374
+ .then(({ known }) => (known ? null : closed()), closed)
375
+ .catch(() => {})
376
+ continue
377
+ }
378
+ const job = running.get(id)
379
+ if (job) {
380
+ job.canceled = true
381
+ job.child.kill("SIGTERM")
382
+ } else if (serving && id) serving.child.kill("SIGTERM")
383
+ }
384
+ // While the Host stops a job Kriya answers this poll at once: don't hammer it
385
+ if (canceling.size && !next.dispatch && next.cancel?.every((id) => canceling.has(id))) await new Promise((done) => setTimeout(done, options.once ? 0 : 2_000))
386
+ for (const id of canceling) if (!next.cancel?.includes(id)) canceling.delete(id)
387
+ if (next.dispatch) {
388
+ const work = handle(next.dispatch).catch((error) => report(next.dispatch.id, "failed", { error: String(error?.message ?? error).slice(0, 500) }))
389
+ if (options.once) await work
390
+ }
391
+ } catch (error) {
392
+ if (signal?.aborted) break
393
+ if (error instanceof KriyaError && error.status === 404) {
394
+ log("kriya daemon: the Control Center isn't on for this Kriya yet; trying again in a minute.")
395
+ await new Promise((done) => setTimeout(done, 60_000))
396
+ } else {
397
+ const wait = BACKOFF_MS[Math.min(failures++, BACKOFF_MS.length - 1)]
398
+ log(`kriya daemon: ${error.message}; trying again in ${wait / 1000} s`)
399
+ await new Promise((done) => setTimeout(done, wait))
400
+ }
401
+ }
402
+ if (options.once) break
403
+ }
404
+ for (const { child: proc } of running.values()) proc.kill("SIGTERM")
405
+ serving?.child.kill("SIGTERM")
406
+ }
407
+
408
+ /* ─────────── terminal → Kriya: what this kriya process runs ─────────── */
409
+
410
+ /**
411
+ * Tells Kriya what a kriya process runs (mode, switches, folder name,
412
+ * state; never the task). Fire-and-forget: a Kriya without the Control
413
+ * Center (404) or a failed request changes nothing for the person.
414
+ * @returns {{ end: (status: string, exitCode?: number) => Promise<void> }}
415
+ */
416
+ export const HEARTBEAT_MS = 60_000
417
+
418
+ export function broadcastRun(device, { kind, mode, switches, cwd = process.cwd(), env = process.env, fetchCall = call, heartbeatMs = HEARTBEAT_MS }) {
419
+ if (!device || env.KRIYA_BROADCAST === "off") return { end: async () => {} }
420
+ const dispatchId = /^[0-9a-f-]{36}$/.test(env.KRIYA_DISPATCH_ID ?? "") ? env.KRIYA_DISPATCH_ID : undefined
421
+ const base = {
422
+ localId: randomUUID(),
423
+ source: dispatchId ? "dispatch" : "terminal",
424
+ kind,
425
+ ...(MODES.has(mode) && { mode }),
426
+ switches,
427
+ project: basename(cwd).slice(0, 80),
428
+ ...(dispatchId && { dispatchId }),
429
+ }
430
+ const post = (body) => fetchCall(device.url, "POST", "/runs", { token: device.token, body, signal: AbortSignal.timeout(5_000) }).catch(() => {})
431
+ const started = post({ ...base, status: "running" })
432
+ // A heartbeat while it runs: a process that dies without a word shows as lost, not running forever
433
+ const beat = setInterval(() => post({ ...base, status: "running" }), heartbeatMs)
434
+ beat.unref?.()
435
+ return {
436
+ end: async (status, exitCode) => {
437
+ clearInterval(beat)
438
+ await started
439
+ await post({ ...base, status, ...(Number.isInteger(exitCode) && { exitCode }) })
440
+ },
441
+ }
442
+ }
443
+
444
+ export { BASE_PATH }
445
+
446
+ /* ─────────── kriya daemon install: run it in the background ─────────── */
447
+
448
+ export const LAUNCHD_LABEL = "ai.kriya.harness.daemon"
449
+ const xml = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
450
+
451
+ /**
452
+ * The daemon as a background service, for the person's own login only:
453
+ * a launchd agent on macOS, a systemd user unit on Linux. The folders and
454
+ * --allow-* flags are the ones given to `kriya daemon install`.
455
+ * @returns {{ path: string, content: string, start: string[][], stop: string[][] } | null} null on other systems
456
+ */
457
+ export function serviceDefinition({ platform = process.platform, home = homedir(), node = process.execPath, bin, args }) {
458
+ const command = [node, bin, "daemon", ...args]
459
+ const logs = join(home, ".kriya", "daemon.log")
460
+ if (platform === "darwin") {
461
+ const path = join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`)
462
+ const content = `<?xml version="1.0" encoding="UTF-8"?>
463
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
464
+ <plist version="1.0">
465
+ <dict>
466
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
467
+ <key>ProgramArguments</key>
468
+ <array>
469
+ ${command.map((part) => ` <string>${xml(part)}</string>`).join("\n")}
470
+ </array>
471
+ <key>RunAtLoad</key><true/>
472
+ <key>KeepAlive</key><true/>
473
+ <key>StandardOutPath</key><string>${xml(logs)}</string>
474
+ <key>StandardErrorPath</key><string>${xml(logs)}</string>
475
+ </dict>
476
+ </plist>
477
+ `
478
+ return { path, content, start: [["launchctl", "load", "-w", path]], stop: [["launchctl", "unload", "-w", path]] }
479
+ }
480
+ if (platform === "linux") {
481
+ const path = join(home, ".config", "systemd", "user", "kriya-daemon.service")
482
+ const quote = (part) => (/^[\w@%+=:,./-]+$/.test(part) ? part : `"${part.replace(/(["\\$`])/g, "\\$1")}"`)
483
+ const content = `[Unit]
484
+ Description=Kriya Harness daemon (the Control Center)
485
+
486
+ [Service]
487
+ ExecStart=${command.map(quote).join(" ")}
488
+ Restart=on-failure
489
+ StandardOutput=append:${logs}
490
+ StandardError=append:${logs}
491
+
492
+ [Install]
493
+ WantedBy=default.target
494
+ `
495
+ return {
496
+ path,
497
+ content,
498
+ start: [["systemctl", "--user", "daemon-reload"], ["systemctl", "--user", "enable", "--now", "kriya-daemon.service"]],
499
+ stop: [["systemctl", "--user", "disable", "--now", "kriya-daemon.service"]],
500
+ }
501
+ }
502
+ return null
503
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,137 @@
1
+ import { execFileSync } from "node:child_process"
2
+ import { homedir } from "node:os"
3
+ import { join, sep } from "node:path"
4
+
5
+ import { chromeInstalled } from "./browser.js"
6
+ import { call, models, me } from "./api.js"
7
+ import { dumpConfig } from "./launch.js"
8
+ import { CLIENT_VERSION } from "./paths.js"
9
+ import { PROFILES } from "./profiles.js"
10
+ import { readDevice } from "./store.js"
11
+
12
+ // `kriya doctor`: what's needed to run, checked in order, each with a plain
13
+ // fix. Exit code 0 only when every check passes.
14
+
15
+ export const MIN_NODE = [24, 9]
16
+
17
+ // Whether iCloud syncs ~/Desktop and ~/Documents on this Mac
18
+ function icloudDesktop() {
19
+ try {
20
+ return process.platform === "darwin" && execFileSync("defaults", ["read", "com.apple.finder", "FXICloudDriveDesktop"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() === "1"
21
+ } catch {
22
+ return false
23
+ }
24
+ }
25
+
26
+ const within = (dir, parent) => dir === parent || dir.startsWith(`${parent}${sep}`)
27
+
28
+ /** Why `dir` is a poor home for a project, or undefined. Kriya works there; syncing node_modules and builds is what suffers */
29
+ export function syncedFolder(dir, home = homedir(), desktopSynced = icloudDesktop()) {
30
+ const icloud = "this folder is synced by iCloud, which slows installs and builds and can hold files back; a folder like ~/Developer is better for projects"
31
+ if (within(dir, join(home, "Library", "Mobile Documents"))) return icloud
32
+ if (within(dir, join(home, "Library", "CloudStorage"))) return "this folder is synced to the cloud, which slows installs and builds; a folder like ~/Developer is better for projects"
33
+ return desktopSynced && (within(dir, join(home, "Documents")) || within(dir, join(home, "Desktop"))) ? icloud : undefined
34
+ }
35
+
36
+ /** Tiers that all run one model can't step up; undefined when they differ or a name is missing */
37
+ export function tierNote(data) {
38
+ const names = new Set(data.map((m) => m.name))
39
+ return data.length > 1 && names.size === 1 && data[0].name ? `every tier runs one model (${data[0].name}), so a harder task can't step up: set routing.* in the Owner console` : undefined
40
+ }
41
+
42
+ export function nodeOk(version = process.versions.node) {
43
+ const [major, minor] = version.split(".").map(Number)
44
+ return major > MIN_NODE[0] || (major === MIN_NODE[0] && minor >= MIN_NODE[1])
45
+ }
46
+
47
+ // Rows the kriya bundle must keep disabled in every profile (HD-17, HD-02)
48
+ export const MUST_BE_DISABLED = [
49
+ "deepseek-account",
50
+ "llm-deepseek",
51
+ "llm-deepseek-account",
52
+ "web-search-deepseek",
53
+ "web-deepseek-api",
54
+ "session-log-deepseek",
55
+ "otel",
56
+ "session-telemetry-otel",
57
+ // Web UI profile only
58
+ "ui-settings-session-log",
59
+ "account-controller",
60
+ "ui-settings-account",
61
+ "desktop-product-telemetry",
62
+ "product-analytics",
63
+ ]
64
+
65
+ /** The composed rows of a --dump-config: id → whether the row is disabled (literally true). */
66
+ export function rowStates(yaml) {
67
+ const rows = new Map()
68
+ let current = null
69
+ for (const line of yaml.split("\n")) {
70
+ const id = /^(?:\s*)- id: ([\w-]+)\s*$/.exec(line)
71
+ if (id) {
72
+ current = id[1]
73
+ if (!rows.has(current)) rows.set(current, false)
74
+ continue
75
+ }
76
+ if (current && /^\s+disabled: true\s*$/.test(line)) rows.set(current, true)
77
+ }
78
+ return rows
79
+ }
80
+
81
+ /** @param {{ say?: (line: string) => void }} [io] */
82
+ export async function doctor(io = {}) {
83
+ const say = io.say ?? ((line) => process.stdout.write(`${line}\n`))
84
+ let ok = true
85
+ const check = (pass, label, fix) => {
86
+ say(`${pass ? "ok " : "FAIL"} ${label}${pass || !fix ? "" : ` — ${fix}`}`)
87
+ if (!pass) ok = false
88
+ }
89
+
90
+ check(
91
+ nodeOk(),
92
+ `Node ${process.versions.node} (needs ${MIN_NODE.join(".")} or later)`,
93
+ "install Node 24.9 or later from nodejs.org"
94
+ )
95
+ say(`ok Kriya Harness ${CLIENT_VERSION}`)
96
+
97
+ for (const profile of Object.keys(PROFILES)) {
98
+ try {
99
+ const rows = rowStates(dumpConfig(profile))
100
+ const open = MUST_BE_DISABLED.filter((id) => rows.has(id) && !rows.get(id))
101
+ check(open.length === 0, `profile ${profile} composes`, `rows not disabled: ${open.join(", ")}`)
102
+ } catch (error) {
103
+ check(false, `profile ${profile} composes`, error.message)
104
+ }
105
+ }
106
+
107
+ // Not a failure: everything else works without it
108
+ say(`ok agent's browser: ${chromeInstalled() ? "ready" : "off (install Chrome, Edge, Brave or Chromium to turn it on)"}`)
109
+
110
+ const synced = syncedFolder(process.cwd())
111
+ if (synced) say(`note ${synced}`)
112
+
113
+ const device = readDevice()
114
+ check(!!device, device ? `signed in to ${device.url}` : "signed in", "run kriya login")
115
+ if (device) {
116
+ try {
117
+ const who = await me(device.url, device.token)
118
+ check(true, `Kriya account reachable (${who.displayName ?? "you"} · ${who.agent?.name ?? "agent"})`)
119
+ check(
120
+ who.harness?.enabled === true,
121
+ "Kriya Harness on for this account",
122
+ "Kriya Harness isn't on for your plan yet"
123
+ )
124
+ const list = await models(device.url, device.token)
125
+ const tiers = list.data.map((model) => model.id)
126
+ check(tiers.length > 0, `gateway models: ${tiers.join(", ") || "none"}`, "your plan allows no models")
127
+ const single = tierNote(list.data)
128
+ if (single) say(`note ${single}`)
129
+ // An empty report writes nothing: 400 means the route is on, 404 that it's switched off
130
+ const live = await call(device.url, "POST", "/live", { token: device.token, body: {} }).catch((error) => error.status)
131
+ say(`ok Remote Control on Kriya: ${live === 404 ? "off (harness.remoteControl in the Owner console)" : "on"}`)
132
+ } catch (error) {
133
+ check(false, "Kriya account reachable", error.message)
134
+ }
135
+ }
136
+ return ok
137
+ }