@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
package/src/loop.js ADDED
@@ -0,0 +1,428 @@
1
+ import { readFileSync, writeFileSync } from "node:fs"
2
+
3
+ import { RANK } from "./failure.js"
4
+ import { checkPremortem } from "./sentinel.js"
5
+ import { PLAN_LIMITS, taskKind, TASK_KINDS } from "./strict.js"
6
+ import { confirmCheck, markStalled, MAX_ATTEMPTS, readProgress, stepLabel, trimOutput, verdict, VerifyError, writeProgress } from "./verify.js"
7
+ import { projectRoot } from "./skill-switches.js"
8
+
9
+ // The Kriya loop's plan and steps (H14c; KRIYA_LOOP.md in the Kriya
10
+ // repository). The task is split into at most MAX_STEPS ordered steps
11
+ // (kriya_plan); each step is built by a fresh agent that sees only the
12
+ // goal, the plan and its own step (kriya_step), then checked by the
13
+ // harness itself with the project's confirmed check. A failure goes back
14
+ // to a new builder with its output, up to MAX_ATTEMPTS runs; then the step
15
+ // is blocked. Code decides pass, retry and blocked; the model only builds.
16
+
17
+ export const MAX_STEPS = 7
18
+ // A session may re-plan twice: a new plan starts its steps over, so an
19
+ // unlimited re-plan would undo "blocked" and the spend bound with it
20
+ export const MAX_PLANS = 3
21
+ const TITLE = 120
22
+ const DONE_WHEN = 300
23
+ const GOAL = 600
24
+ const FILES = 12
25
+ const MAX_ACCEPTANCE = 3
26
+
27
+ // A step's builder is bounded by code, apart from the turn budget (which
28
+ // gives every agent 150 steps and 60 minutes, so 4 runs of one step could
29
+ // take 4 hours with nothing to show). Found on a real long task: a step-1
30
+ // builder with no confirmed check spent 100 steps and 17 minutes on
31
+ // screenshots and contrast audits while the parent showed one pending call.
32
+ // Near the limit the builder is told once to wrap up; at the limit its next
33
+ // step is refused and the harness's check runs on what it left.
34
+ const whole = (value, fallback) => {
35
+ const n = Number(value)
36
+ return Number.isSafeInteger(n) && n > 0 ? n : fallback
37
+ }
38
+ /** One builder's limits, from the launch environment; defaults when unset or unusable. */
39
+ export function builderLimits(env = process.env) {
40
+ return { maxSteps: whole(env.KRIYA_BUILDER_STEPS, 40), maxMinutes: whole(env.KRIYA_BUILDER_MINUTES, 15) }
41
+ }
42
+
43
+ // Builds in progress, for the Progress tab: session id → the live record
44
+ // runStep hands to spawn ({ n, attempt, startedAt, steps, last, stopped }).
45
+ // In memory only: a build lives exactly as long as its kriya_step call.
46
+ const building = new Map()
47
+ /** The step being built in a session right now, if any */
48
+ export const liveBuild = (sessionId) => building.get(sessionId)
49
+
50
+ const clean = (value, limit) => (typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, limit) : "")
51
+
52
+ /**
53
+ * Loop v2: the steps a step needs first, as step numbers. Each must be an
54
+ * earlier step, so every plan is a DAG listed in a topological order (no
55
+ * cycle can be written down). Absent: the step before it, as in v1.
56
+ */
57
+ function dependencies(value, n) {
58
+ if (value === undefined) return n > 1 ? [n - 1] : []
59
+ if (!Array.isArray(value)) throw new VerifyError(`Step ${n}: after is a list of earlier step numbers.`)
60
+ const deps = [...new Set(value.map(Number))]
61
+ for (const d of deps) if (!Number.isInteger(d) || d < 1 || d >= n) throw new VerifyError(`Step ${n} can only come after earlier steps (1 to ${n - 1}); list the steps in an order where each needs only steps above it.`)
62
+ return deps.sort((a, b) => a - b)
63
+ }
64
+
65
+ /**
66
+ * A plan as the agent proposed it, checked: a goal and 1..MAX_STEPS steps,
67
+ * each with a title, a done-when sentence and the files it expects to touch;
68
+ * with v2, also the earlier steps each one needs (`after`).
69
+ * With strict, the task contract too: its kind (which bounds the plan), the
70
+ * paths that must not change and commands that must also exit 0. A contract
71
+ * can only add to what must hold; it can't replace the person's check.
72
+ * @returns {{ goal: string, steps: Array<{ title: string, doneWhen: string, files: string[], after?: number[] }>, kind?: string, invariants?: string[], acceptance?: string[] }}
73
+ */
74
+ export function validatePlan(input, { v2 = false, strict = false, defensive = false } = {}) {
75
+ const goal = clean(input?.goal, GOAL)
76
+ if (!goal) throw new VerifyError("A plan needs a goal: one sentence on what the task is for.")
77
+ const steps = Array.isArray(input?.steps) ? input.steps : []
78
+ if (!steps.length) throw new VerifyError("A plan needs at least one step.")
79
+ if (steps.length > MAX_STEPS) throw new VerifyError(`A plan has at most ${MAX_STEPS} steps; merge some, or split the task into separate jobs.`)
80
+ const out = steps.map((step, i) => {
81
+ const title = clean(step?.title, TITLE)
82
+ const doneWhen = clean(step?.done_when ?? step?.doneWhen, DONE_WHEN)
83
+ if (!title) throw new VerifyError(`Step ${i + 1} needs a title.`)
84
+ if (!doneWhen) throw new VerifyError(`Step ${i + 1} needs done_when: what is true when it's finished.`)
85
+ const files = (Array.isArray(step?.files) ? step.files : []).map((f) => clean(f, 300)).filter(Boolean).slice(0, FILES)
86
+ return { title, doneWhen, files, ...(v2 && { after: dependencies(step?.after, i + 1) }) }
87
+ })
88
+ const titles = new Set(out.map((s) => s.title.toLowerCase()))
89
+ if (titles.size !== out.length) throw new VerifyError("Two steps have the same title; each step is one distinct piece of work.")
90
+ const { premortem, problem } = defensive ? checkPremortem(input?.premortem, out.length) : {}
91
+ if (problem) throw new VerifyError(problem)
92
+ return { goal, steps: out, ...(strict && contract(input, goal, out.length)), ...(premortem && { premortem }) }
93
+ }
94
+
95
+ function contract(input, goal, steps) {
96
+ const kind = input?.kind ?? taskKind(goal)
97
+ if (!TASK_KINDS.includes(kind)) throw new VerifyError(`kind is one of: ${TASK_KINDS.join(", ")}.`)
98
+ if (steps > PLAN_LIMITS[kind]) throw new VerifyError(`A ${kind} plan has at most ${PLAN_LIMITS[kind]} steps; do it directly, or name the kind that fits.`)
99
+ const list = (value, limit, size) => (Array.isArray(value) ? value : []).map((v) => clean(v, size)).filter(Boolean).slice(0, limit)
100
+ const acceptance = list(input?.acceptance, MAX_ACCEPTANCE, 300)
101
+ return { kind, invariants: list(input?.invariants, FILES, 300), acceptance }
102
+ }
103
+
104
+ export { stepLabel }
105
+
106
+ /**
107
+ * Saves the session's plan beside its runs. A new plan starts its steps
108
+ * over; the earlier plans and runs are kept, and at most MAX_PLANS are made.
109
+ */
110
+ export function savePlan(cwd, sessionId, input, now = () => new Date(), options = {}) {
111
+ const plan = validatePlan(input, options)
112
+ const root = projectRoot(cwd)
113
+ const progress = readProgress(root, sessionId)
114
+ const earlier = [...(progress.earlier ?? []), ...(progress.plan ? [{ plan: progress.plan, runs: progress.runs }] : [])]
115
+ if (earlier.length >= MAX_PLANS) throw new VerifyError(`This session already made ${MAX_PLANS} plans; stop and tell the person where it stands.`)
116
+ writeProgress(root, sessionId, { ...progress, earlier, plan: { ...plan, at: now().toISOString() }, runs: progress.plan ? [] : progress.runs })
117
+ return plan
118
+ }
119
+
120
+ /**
121
+ * A flow from Kriya (SD-14 in the Kriya repository): the person's own plan,
122
+ * which the daemon hands over in a file. While one is set it is the session's
123
+ * plan as written, so the model can't rewrite it.
124
+ */
125
+ export function seededPlan(env = process.env) {
126
+ if (!env.KRIYA_SEED_PLAN) return undefined
127
+ try {
128
+ return JSON.parse(readFileSync(env.KRIYA_SEED_PLAN, "utf8"))
129
+ } catch {
130
+ return undefined
131
+ }
132
+ }
133
+
134
+ /** Where a seeded plan stands, for the daemon to report; a safety net, never a gate */
135
+ export function writeSnapshot(cwd, sessionId, { current, env = process.env } = {}) {
136
+ if (!env.KRIYA_PROGRESS_FILE) return
137
+ try {
138
+ const plan = planStatus(cwd, sessionId)?.map((s) => ({ ...s, ...(s.n === current && !s.building && { building: { attempt: s.attempts + 1 } }) }))
139
+ writeFileSync(env.KRIYA_PROGRESS_FILE, JSON.stringify({ plan }))
140
+ } catch {
141
+ // The run doesn't depend on being reported
142
+ }
143
+ }
144
+
145
+ export function readPlan(cwd, sessionId) {
146
+ return readProgress(projectRoot(cwd), sessionId).plan
147
+ }
148
+
149
+ /** Where each step stands, from the recorded runs */
150
+ export function planStatus(cwd, sessionId) {
151
+ const progress = readProgress(projectRoot(cwd), sessionId)
152
+ if (!progress.plan) return undefined
153
+ const { steps } = verdict(progress)
154
+ const live = building.get(sessionId)
155
+ const rows = []
156
+ progress.plan.steps.forEach((step, i) => {
157
+ const label = stepLabel(progress.plan, i + 1)
158
+ const found = steps.find((s) => s.step === label)
159
+ // Built by kriya_step with no check confirmed: done for ordering, never a pass
160
+ const built = !found && progress.built?.some((b) => b.step === label)
161
+ // v2: a step that needs a blocked or skipped step is skipped; one pass in plan order suffices, since deps point back
162
+ const stuck = !found && step.after?.some((d) => ["blocked", "skipped"].includes(rows[d - 1].status))
163
+ rows.push({
164
+ n: i + 1,
165
+ title: step.title,
166
+ status: stuck ? "skipped" : (found?.status ?? (built ? "built" : "not started")),
167
+ attempts: found?.attempts ?? 0,
168
+ ...(step.after && { after: step.after }),
169
+ ...(live?.n === i + 1 && { building: { attempt: live.attempt, steps: live.steps, startedAt: live.startedAt, ...(live.last && { last: live.last }) } }),
170
+ })
171
+ })
172
+ return rows
173
+ }
174
+
175
+ /**
176
+ * The step a stopping agent should have gone on to, if any (loop guard). A
177
+ * blocked step ends a v1 plan, as the guidance says; in v2 only the steps
178
+ * that need it. Nothing while a step is being built.
179
+ */
180
+ export function nextStep(rows) {
181
+ if (!rows || rows.some((r) => r.building)) return undefined
182
+ const ready = (r) => (r.after ? r.after.every((d) => ["pass", "built"].includes(rows[d - 1].status)) : !rows.some((o) => o.n < r.n && o.status === "blocked"))
183
+ return rows.find((r) => ["not started", "fail"].includes(r.status) && ready(r))
184
+ }
185
+
186
+ /**
187
+ * Loop v2, long tasks: where the work stands, from the loop's own records,
188
+ * for a late system-prompt section that compaction never condenses. A small
189
+ * context window loses older turns to summaries; this keeps the goal, every
190
+ * step's status and the next step in front of the agent. Empty without a plan.
191
+ */
192
+ export function loopStateText(cwd, sessionId) {
193
+ const progress = readProgress(projectRoot(cwd), sessionId)
194
+ if (!progress.plan) return ""
195
+ const rows = planStatus(cwd, sessionId)
196
+ const STATE = { pass: "passed", fail: "failing", blocked: "blocked", skipped: "skipped", built: "built, not checked (no check confirmed)", "not started": "not started" }
197
+ const next = rows.find((r) => r.status === "not started" || r.status === "fail")
198
+ const last = progress.runs.at(-1)
199
+ const lines = [
200
+ "Where this task stands, kept by Kriya Harness from its own check runs (it outranks any summary of the conversation):",
201
+ `Goal: ${progress.plan.goal}`,
202
+ ...rows.map((r) => `${r.n}. ${r.title}: ${STATE[r.status] ?? r.status}${r.attempts ? ` (${r.attempts} run${r.attempts === 1 ? "" : "s"})` : ""}`),
203
+ next ? `Next: kriya_step with step ${next.n}.` : "Every step has passed, been blocked or been skipped: report each step's result.",
204
+ ]
205
+ if (last) lines.push(`Last check: ${last.step}, ${last.status === "pass" ? "passed" : `failed (exit ${last.exitCode ?? "none"}${last.kind ? `, ${last.kind}` : ""})`}.`)
206
+ return lines.join("\n")
207
+ }
208
+
209
+ /** What a fresh builder is told: the goal, the plan, its one step and, on a retry, what failed; with v2, the person's confirmed rules */
210
+ export function builderPrompt(plan, n, previous, rules = [], { limits = builderLimits(), checked = true, briefing = [] } = {}) {
211
+ const step = plan.steps[n - 1]
212
+ const lines = [
213
+ `You are building one step of a larger task. Do only this step, then stop.`,
214
+ "",
215
+ `Goal of the task: ${plan.goal}`,
216
+ "",
217
+ "The plan (for context; other steps are done by others):",
218
+ ...plan.steps.map((s, i) => `${i + 1}. ${s.title}${i + 1 === n ? " <- your step" : ""}`),
219
+ "",
220
+ `Your step: ${n}. ${step.title}`,
221
+ `It is done when: ${step.doneWhen}`,
222
+ ]
223
+ if (step.files.length) lines.push(`Files it is expected to touch: ${step.files.join(", ")}`)
224
+ if (plan.invariants?.length) lines.push(`These must not change: ${plan.invariants.join(", ")}`)
225
+ if (plan.acceptance?.length) lines.push(`These commands must also exit 0: ${plan.acceptance.join("; ")}`)
226
+ if (plan.premortem) {
227
+ lines.push("", "The plan's pre-mortem, which this work must defend against:")
228
+ for (const f of plan.premortem.failures) lines.push(`- Could fail: ${f.what} (proved by ${f.coveredBy})`)
229
+ lines.push(`- Shares this surface: ${plan.premortem.blastRadius.join("; ")}`, `- Bad inputs to handle: ${plan.premortem.negatives.join("; ")}`)
230
+ }
231
+ if (briefing.length) lines.push("", ...briefing)
232
+ if (rules.length) lines.push("", "Rules for this project, confirmed by the person:", ...rules)
233
+ lines.push(
234
+ "",
235
+ "Read the code you need, make the change, and keep it small. Don't change other steps' work unless your step needs it.",
236
+ "Don't call kriya_plan or kriya_step: you are the step. You may call kriya_verify to test your change before you finish.",
237
+ "When you finish, the harness runs the project's check; that result, not your summary, decides whether the step passes. End with two or three sentences on what you changed.",
238
+ `You have at most ${limits.maxSteps} steps and ${limits.maxMinutes} minutes. At the limit you are stopped and the check runs on what you left, so make the step's core change first and polish after.`,
239
+ "Don't leave servers or browsers running: start one only with run_in_background, and stop it before you finish."
240
+ )
241
+ if (!checked)
242
+ lines.push(
243
+ "No check is confirmed for this project, so nothing judges this step after you. Don't spend steps on open-ended manual QA (screenshots, pixel or contrast audits, repeated browser runs): " +
244
+ "stop once the step's files are written and they build or load without errors. If the project has no build or test script yet, add a real one (e.g. in package.json): Kriya offers it to the person as the project's check."
245
+ )
246
+ if (previous)
247
+ lines.push(
248
+ "",
249
+ `This is attempt ${previous.attempt + 1} of ${MAX_ATTEMPTS}. The previous attempt failed the project's check (\`${previous.command}\`, ${previous.timedOut ? "timed out" : `exit ${previous.exitCode}`}${previous.kind ? `; failure class: ${previous.kind}` : ""}). ${previous.kind ? "The lines that name the failure" : "Its output"}:`,
250
+ "```",
251
+ trimOutput(previous.output, 3000),
252
+ "```",
253
+ "Find the cause in the code and fix it; the files may already contain the previous attempt's changes."
254
+ )
255
+ if (previous?.kind === "tests changed")
256
+ lines.push("The check passed only with changed tests or check files; on the originals it fails (above). Fix the code so the original tests pass; don't change existing tests.")
257
+ if (previous?.note) lines.push(previous.note)
258
+ return lines.join("\n")
259
+ }
260
+
261
+ // Attempts in a row that don't parse or type-check before a step's files go back
262
+ export const BROKEN_ATTEMPTS = 2
263
+
264
+ // How often one step may come back "interrupted" before its builders count as attempts again
265
+ export const MAX_INTERRUPTIONS = 2
266
+
267
+ /** One builder's record beside the runs: what the bench and KRHE count; never shown to a model */
268
+ function noteBuilder(root, sessionId, builder) {
269
+ const progress = readProgress(root, sessionId)
270
+ writeProgress(root, sessionId, { ...progress, builders: [...(progress.builders ?? []), builder] })
271
+ }
272
+
273
+ /** Counts one interruption of a step; false once the step has had MAX_INTERRUPTIONS */
274
+ function noteInterruption(root, sessionId, label) {
275
+ const progress = readProgress(root, sessionId)
276
+ const count = progress.interrupted?.[label] ?? 0
277
+ if (count >= MAX_INTERRUPTIONS) return false
278
+ writeProgress(root, sessionId, { ...progress, interrupted: { ...progress.interrupted, [label]: count + 1 } })
279
+ return true
280
+ }
281
+
282
+ const textOf = (blocks) =>
283
+ (Array.isArray(blocks) ? blocks : [])
284
+ .filter((b) => b?.type === "text" && typeof b.text === "string")
285
+ .map((b) => b.text)
286
+ .join("\n")
287
+ .trim()
288
+
289
+ /**
290
+ * Runs one plan step to pass or blocked: a fresh builder, the harness's
291
+ * check, and a new builder with the failure until MAX_ATTEMPTS runs.
292
+ * With v2: only the step's own dependencies must have passed (one that is
293
+ * blocked or skipped skips it, building nothing); each attempt's files are
294
+ * saved, and an attempt that fails further from passing than the best one
295
+ * so far (RANK: syntax < type < assertion) is set aside, the files going
296
+ * back to the best attempt's before the next builder. Same attempt bound.
297
+ * Each builder gets a live record (spawn's third argument; the Progress tab
298
+ * reads it) and is bounded by `limits`; one stopped at its limit is still
299
+ * checked, and the result says so. `hasCheck`: whether a check is confirmed.
300
+ * With the guard (KRIYA_LOOP_GUARD=on): a step resumed after an interruption
301
+ * starts from its last recorded failure; a builder that died on an error
302
+ * before changing a file isn't an attempt (the step comes back "interrupted",
303
+ * at most MAX_INTERRUPTIONS times); and more builders stop being spent when
304
+ * they can't help: the same failure twice with no file changed, or a check
305
+ * that can't run. Same attempt bound; only ever fewer builders.
306
+ * With guard.restore (strict): a step is one transaction. Two attempts in a
307
+ * row that break the build go back to the files the step began with, and a
308
+ * blocked step leaves them that way; every replaced state stays in `kriya
309
+ * undo --list`. Nothing but Kriya's own restore touches the person's git.
310
+ * @param {{ cwd: string, sessionId: string, n: number, spawn: (prompt: string, label: string, live: { n: number, attempt: number, startedAt: number, steps: number, last?: string, stopped?: string }) => Promise<{ output: any[], stopReason?: string }>, verify: (label: string) => Promise<any>, v2?: { snapshot?: (label: string) => Promise<string | undefined>, restore?: (tree: string, label: string) => Promise<unknown>, rules?: string[] }, guard?: { snapshot?: (label: string) => Promise<string | undefined>, restore?: (tree: string, label: string) => Promise<unknown>, briefing?: (step: any) => Promise<string[]> }, hasCheck?: boolean, limits?: { maxSteps: number, maxMinutes: number }, now?: () => number }} input
311
+ */
312
+ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, hasCheck = true, limits = builderLimits(), now = Date.now, pickCheck }) {
313
+ const plan = readPlan(cwd, sessionId)
314
+ if (!plan) throw new VerifyError("There's no plan yet: call kriya_plan first.")
315
+ if (!Number.isInteger(n) || n < 1 || n > plan.steps.length) throw new VerifyError(`The plan has steps 1 to ${plan.steps.length}.`)
316
+ const status = planStatus(cwd, sessionId)
317
+ const deps = plan.steps[n - 1].after
318
+ if (deps) {
319
+ const stuck = deps.map((d) => status[d - 1]).find((s) => s.status === "blocked" || s.status === "skipped")
320
+ if (stuck) return { status: "skipped", step: n, title: plan.steps[n - 1].title, builders: [], note: `It needs step ${stuck.n} (${stuck.title}), which is ${stuck.status}, so nothing was built.` }
321
+ const open = deps.map((d) => status[d - 1]).find((s) => s.status !== "pass" && s.status !== "built")
322
+ if (open) throw new VerifyError(`Step ${n} needs step ${open.n} (${open.title}) first, and it hasn't passed yet.`)
323
+ } else {
324
+ const open = status.find((s) => s.n < n && !["pass", "blocked", "built"].includes(s.status))
325
+ if (open) throw new VerifyError(`Steps run in order: step ${open.n} (${open.title}) isn't finished yet.`)
326
+ }
327
+ const label = stepLabel(plan, n)
328
+ const builders = []
329
+ const root = projectRoot(cwd)
330
+ const save = v2?.snapshot ?? guard?.snapshot
331
+ const lastRun = guard && status[n - 1].status === "fail" ? readProgress(root, sessionId).runs.findLast((r) => r.step === label) : undefined
332
+ let previous = lastRun?.excerpt
333
+ ? { attempt: status[n - 1].attempts, command: lastRun.command, exitCode: lastRun.exitCode, timedOut: lastRun.timedOut, output: lastRun.excerpt, kind: lastRun.kind, sig: lastRun.sig }
334
+ : undefined
335
+ let best
336
+ // The files the next builder starts from
337
+ let start = guard ? await save?.(`before step ${n}`) : undefined
338
+ const base = start
339
+ const briefing = (await guard?.briefing?.(plan.steps[n - 1])) ?? []
340
+ let broken = 0
341
+ const rollBack = async (why) => {
342
+ if (!guard?.restore || !base) return false
343
+ await guard.restore(base, why)
344
+ const progress = readProgress(root, sessionId)
345
+ writeProgress(root, sessionId, { ...progress, rollbacks: (progress.rollbacks ?? 0) + 1 })
346
+ return true
347
+ }
348
+ for (;;) {
349
+ const before = status[n - 1]
350
+ if (before.status === "pass") return { status: "pass", step: n, title: plan.steps[n - 1].title, attempts: before.attempts, builders, note: "This step already passed." }
351
+ const live = { n, attempt: builders.length + 1, startedAt: now(), steps: 0 }
352
+ building.set(sessionId, live)
353
+ let built
354
+ try {
355
+ built = await spawn(builderPrompt(plan, n, previous, v2?.rules, { limits, checked: hasCheck, briefing }), `Step ${n}: ${plan.steps[n - 1].title}`, live)
356
+ } finally {
357
+ if (building.get(sessionId) === live) building.delete(sessionId)
358
+ }
359
+ builders.push({ stopReason: built.stopReason ?? "completed", summary: textOf(built.output).slice(-600), steps: live.steps, ...(live.stopped && { limit: live.stopped }) })
360
+ noteBuilder(root, sessionId, { step: label, stopReason: builders.at(-1).stopReason, steps: live.steps, ms: now() - live.startedAt, ...(live.tokens && { tokens: live.tokens }), ...(live.stopped && { limit: live.stopped }) })
361
+ const tree = await save?.(`attempt ${builders.length} of step ${n}`)
362
+ const untouched = tree !== undefined && tree === start
363
+ if (guard && built.stopReason === "error" && untouched && noteInterruption(root, sessionId, label))
364
+ return { status: "interrupted", step: n, title: plan.steps[n - 1].title, builders, note: "The builder stopped on an error before changing any file, so this wasn't an attempt and nothing was checked." }
365
+ let checked = await verify(label)
366
+ // A project built from nothing has no check until a step writes one: the person picks it now, so this step
367
+ // is judged. Asked once a session; the answer comes from the person's UI, never from the model
368
+ if (checked.status === "not configured" && pickCheck && checked.suggestions?.length && !readProgress(root, sessionId).checkAsked) {
369
+ const command = await pickCheck(checked.suggestions)
370
+ if (command) {
371
+ confirmCheck(cwd, command)
372
+ hasCheck = true
373
+ checked = await verify(label)
374
+ } else writeProgress(root, sessionId, { ...readProgress(root, sessionId), checkAsked: true })
375
+ }
376
+ if (checked.status === "not configured") {
377
+ // Recorded apart from check runs, so the plan moves on and the verdict stays "not checked"
378
+ const progress = readProgress(root, sessionId)
379
+ progress.built = [...(progress.built ?? []).filter((b) => b.step !== label), { step: label, at: new Date(now()).toISOString() }]
380
+ writeProgress(root, sessionId, progress)
381
+ return { status: "not checked", step: n, title: plan.steps[n - 1].title, builders, suggestions: checked.suggestions }
382
+ }
383
+ const undone = checked.status === "blocked" && (await rollBack(`step ${n} blocked`))
384
+ // Steps built before there was a check: the check covers the whole project, so they're judged by a run of their own
385
+ if (checked.status === "pass") {
386
+ const { built = [] } = readProgress(root, sessionId)
387
+ const judged = verdict(readProgress(root, sessionId)).steps
388
+ for (const b of built.filter((b) => !judged.some((s) => s.step === b.step))) checked.verdict = (await verify(b.step)).verdict
389
+ }
390
+ if (checked.status === "pass" || checked.status === "blocked")
391
+ return { status: checked.status, step: n, title: plan.steps[n - 1].title, attempts: checked.attempts, builders, command: checked.command, output: checked.output ?? "", verdict: checked.verdict, ...(undone && { rolledBack: true }) }
392
+ const earlier = previous
393
+ previous = { attempt: checked.attempts, command: checked.command, exitCode: checked.exitCode, timedOut: checked.timedOut, output: checked.output, ...(checked.failure && { kind: checked.failure }), ...(checked.signature && { sig: checked.signature }) }
394
+ const repeated = guard && checked.signature && earlier?.sig === checked.signature
395
+ // A builder that died on an error says nothing about the code; its attempts just run out
396
+ // Only exit 126/127 proves the command can't run; ENOENT or a missing module can be the code's own bug
397
+ const cantRun = checked.exitCode === 126 || checked.exitCode === 127
398
+ if (repeated && built.stopReason !== "error" && (untouched || cantRun)) {
399
+ const reason = untouched ? "the same failure again with no file changed" : "the check can't run on this machine"
400
+ const after = markStalled(root, sessionId, reason)
401
+ const undone = await rollBack(`step ${n} blocked`)
402
+ return { status: "blocked", step: n, title: plan.steps[n - 1].title, attempts: checked.attempts, builders, command: checked.command, output: checked.output ?? "", verdict: after.status, stalled: reason, ...(undone && { rolledBack: true }) }
403
+ }
404
+ if (repeated) previous.note = "This is the same failure as the attempt before it, so that approach didn't work: find another cause before changing code."
405
+ start = tree
406
+ broken = ["syntax", "type"].includes(checked.failure) ? broken + 1 : 0
407
+ if (broken >= BROKEN_ATTEMPTS && (await rollBack(`attempts ${checked.attempts - 1} and ${checked.attempts} of step ${n} broke the build`))) {
408
+ broken = 0
409
+ start = base
410
+ builders.at(-1).rolledBack = true
411
+ previous.note = `The last ${BROKEN_ATTEMPTS} attempts broke the build, so all their changes were undone: the files are as they were before this step. Start again, smaller, and run the check as you go.`
412
+ }
413
+ if (v2) {
414
+ const rank = RANK[checked.failure] ?? RANK.unknown
415
+ if (best?.tree && v2.restore && rank < best.rank) {
416
+ await v2.restore(best.tree, `back to attempt ${best.attempt} of step ${n}`)
417
+ builders.at(-1).setAside = true
418
+ start = best.tree
419
+ previous = {
420
+ ...best.previous,
421
+ attempt: checked.attempts,
422
+ note: `Attempt ${checked.attempts} failed further from passing (${checked.failure}) than attempt ${best.attempt} (${best.previous.kind}), so its changes were set aside: the files are as attempt ${best.attempt} left them, and the output above is that attempt's. Try a different fix.`,
423
+ }
424
+ } else best = { rank, tree, attempt: checked.attempts, previous }
425
+ }
426
+ status[n - 1] = { ...before, status: "fail", attempts: checked.attempts }
427
+ }
428
+ }
package/src/modes.js ADDED
@@ -0,0 +1,128 @@
1
+ // Kriya Harness modes: how much the agent may do on its own. Each mode is one
2
+ // sandbox mode and one approval policy of DeepSeek Harness, set through the
3
+ // kriya bundle's rows (bundle/cordis.patch.yml) from the launch variables
4
+ // below; DSH itself isn't edited. In DSH, approval `never` refuses anything
5
+ // that would need approval (it never allows it), so only `full` leaves the
6
+ // folder sandbox, and only when the person asks for it by name.
7
+
8
+ export const MODES = {
9
+ ask: {
10
+ sandbox: "workspace-write",
11
+ approval: "ask",
12
+ preset: "ask",
13
+ label: "Ask",
14
+ what: "Works in this folder and asks before anything beyond it, here or in Kriya on your phone.",
15
+ },
16
+ auto: {
17
+ sandbox: "workspace-write",
18
+ approval: "never",
19
+ preset: "folder-auto",
20
+ label: "Auto",
21
+ what: "Works in this folder without asking; anything that would need your OK is refused instead.",
22
+ },
23
+ read: {
24
+ sandbox: "read-only",
25
+ approval: "never",
26
+ preset: "read-only",
27
+ label: "Read only",
28
+ what: "Reads and answers; changes no file.",
29
+ },
30
+ plan: {
31
+ sandbox: "read-only",
32
+ approval: "never",
33
+ preset: "read-only",
34
+ label: "Plan",
35
+ what: "Explores and writes a step-by-step plan; changes no file.",
36
+ },
37
+ full: {
38
+ sandbox: "danger-full-access",
39
+ approval: "never",
40
+ preset: "full-access",
41
+ label: "Full access",
42
+ what: "No sandbox and no questions: it can change anything you can.",
43
+ },
44
+ }
45
+
46
+ export const DEFAULT_MODE = "ask"
47
+
48
+ // The Web UI starts in one of these; it plans with DSH's own /plan instead
49
+ export const APP_MODES = ["ask", "auto", "read", "full"]
50
+
51
+ export const FULL_ACCESS_WARNING = `Full access: the agent runs commands and changes files anywhere you can,
52
+ with no sandbox and without asking. Use it only on a machine you can afford
53
+ to change.`
54
+
55
+ // `kriya run --mode plan`: the job, asked as a plan. The read-only sandbox
56
+ // and the `never` policy enforce it; these words only say what's wanted
57
+ export function planJob(job) {
58
+ return `Plan only. Explore this folder as much as you need, then reply with a numbered, step-by-step plan for the task below: what you'd change, where, and how you'd check it. Don't change any file.
59
+
60
+ Task: ${job}`
61
+ }
62
+
63
+ export class ModeError extends Error {}
64
+
65
+ /** The mode named by `--mode`, else the default; throws ModeError for an unknown name. */
66
+ export function parseMode(value, allowed = Object.keys(MODES)) {
67
+ if (value === undefined) return DEFAULT_MODE
68
+ if (!allowed.includes(value))
69
+ throw new ModeError(`--mode takes one of: ${allowed.join(", ")}.`)
70
+ return value
71
+ }
72
+
73
+ /** The launch variables the kriya bundle's sandbox, approval and preset rows read. */
74
+ export function modeEnv(name) {
75
+ const mode = MODES[name] ?? MODES[DEFAULT_MODE]
76
+ return {
77
+ KRIYA_SANDBOX: mode.sandbox,
78
+ KRIYA_APPROVAL: mode.approval,
79
+ KRIYA_PRESET: mode.preset,
80
+ }
81
+ }
82
+
83
+ // The Kriya loop's verify step (the bundle's kriya-loop row reads
84
+ // KRIYA_LOOP), the turn budget (KRIYA_BUDGET) and the kept request
85
+ // (KRIYA_ANCHOR). Harness upgrade U10 (owner, 2026-11-04: "B4 is our
86
+ // winner"): the loop and the budget are on unless --no-loop / --no-budget
87
+ // or KRIYA_LOOP=off / KRIYA_BUDGET=off; --anchor stays opt-in (unmeasured).
88
+ // A flag beats the environment, which beats the default
89
+ export const SWITCHES = [
90
+ ["loop", "KRIYA_LOOP", true],
91
+ ["budget", "KRIYA_BUDGET", true],
92
+ ["anchor", "KRIYA_ANCHOR", false],
93
+ // Kriya loop v2 (KRIYA_LOOP_V2.md): opt-in until measured; needs the loop
94
+ ["loop-v2", "KRIYA_LOOP_V2", false],
95
+ // The loop guard (KRIYA_LOOP.md): on (owner, 2026-11-05); needs the loop
96
+ ["loop-guard", "KRIYA_LOOP_GUARD", true],
97
+ // The strict coding loop, reconnaissance and just-in-time tools
98
+ // (KRIYA_CODING_HARNESS_REPORT.md): on (owner, 2026-11-05, unmeasured on a real model); they need the loop
99
+ ["strict-loop", "KRIYA_STRICT_LOOP", true],
100
+ // The defensive engine (KRIYA_DEFENSIVE_ENGINE_REPORT.md): turns the strict loop on too
101
+ ["defensive", "KRIYA_DEFENSIVE", true],
102
+ ["recon", "KRIYA_RECON", true],
103
+ ["jit-tools", "KRIYA_JIT_TOOLS", true],
104
+ // The agent's localhost browser (plugins/browser): on (owner, 2026-11-04:
105
+ // the agent must use the browser we built, shown live in Preview, not its
106
+ // own scripts); offered only where Google Chrome is installed
107
+ ["browser-tools", "KRIYA_BROWSER", true],
108
+ // The intent router (plugins/router): on (owner, 2026-11-05, unmeasured)
109
+ ["router", "KRIYA_ROUTER", true],
110
+ // The Editing Studio (track E): off until the owner turns it on; off, nothing
111
+ // under src/edit/ loads
112
+ ["edit", "KRIYA_EDIT", false],
113
+ ]
114
+
115
+ /** Takes the switch flags out of `args` and sets each switch to "on" or "off" in `env`. */
116
+ export function switchEnv(args, env = process.env) {
117
+ for (const [flag, name, byDefault] of SWITCHES) {
118
+ let value = env[name] === "on" ? true : env[name] === "off" ? false : byDefault
119
+ for (const [form, on] of [[`--${flag}`, true], [`--no-${flag}`, false]]) {
120
+ const at = args.indexOf(form)
121
+ if (at === -1) continue
122
+ args.splice(at, 1)
123
+ value = on
124
+ }
125
+ env[name] = value ? "on" : "off"
126
+ }
127
+ }
128
+
@@ -0,0 +1,71 @@
1
+ import { execFile } from "node:child_process"
2
+ import { promisify } from "node:util"
3
+
4
+ // The Overview tab's data (plugins/overview, workspace panel phase P1 in
5
+ // the Kriya repository's docs/kriya-harness/WORKSPACE_PANEL_SKILLS_PLUGINS.md):
6
+ // where a session runs, read with read-only git. A remote URL can carry a
7
+ // user name or a token (https://user:token@host/…); only the host and the
8
+ // repository path ever leave this file.
9
+
10
+ const run = promisify(execFile)
11
+
12
+ /** The origin remote as { host, path, github }, or null; never any credentials */
13
+ export function parseRemote(url) {
14
+ const text = typeof url === "string" ? url.trim() : ""
15
+ if (!text) return null
16
+ let host
17
+ let path
18
+ // scp-like: git@github.com:owner/repo.git
19
+ const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/.exec(text)
20
+ if (scp && !/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) [, host, path] = scp
21
+ else {
22
+ try {
23
+ const u = new URL(text)
24
+ if (!["https:", "http:", "ssh:", "git:"].includes(u.protocol)) return null
25
+ host = u.hostname
26
+ path = u.pathname
27
+ } catch {
28
+ return null
29
+ }
30
+ }
31
+ path = path.replace(/^\/+/, "").replace(/\.git$/, "").replace(/\/+$/, "")
32
+ if (!host || !/^[\w.-]+$/.test(host) || !/^[\w.-]+(\/[\w.-]+)+$/.test(path)) return null
33
+ return { host: host.toLowerCase(), path, github: host.toLowerCase() === "github.com" }
34
+ }
35
+
36
+ /** The repository's origin remote, parsed, or null (no repository, no origin, or git missing) */
37
+ export async function originOf(root) {
38
+ try {
39
+ const { stdout } = await run("git", ["-C", root, "config", "--get", "remote.origin.url"], {
40
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" },
41
+ timeout: 10_000,
42
+ })
43
+ return parseRemote(stdout)
44
+ } catch {
45
+ return null
46
+ }
47
+ }
48
+
49
+ const num = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : undefined)
50
+
51
+ /** The context and usage figures the token meter keeps for a live session, numbers only */
52
+ export function meterFigures(values = {}) {
53
+ const p = values.contextPressure ?? {}
54
+ const u = values.tokenUsage ?? {}
55
+ const context = { window: num(p.contextWindow), used: num(p.pressureTokens) ?? num(p.projectedTokens) ?? num(p.surfaceTokens) }
56
+ const usage = { input: num(u.uncachedInputTokens), output: num(u.outputTokens), cacheRead: num(u.cacheReadTokens) }
57
+ return {
58
+ context: context.used === undefined ? null : context,
59
+ usage: Object.values(usage).every((v) => v === undefined) ? null : usage,
60
+ }
61
+ }
62
+
63
+ const JOB_LIMIT = 20
64
+
65
+ /** A session's background jobs, newest first, as the panel shows them */
66
+ export function jobRows(jobs = []) {
67
+ return jobs
68
+ .map((j) => ({ id: j.id, kind: j.kind, label: String(j.label ?? "").slice(0, 200), status: j.status, startedAt: j.startedAt, finishedAt: j.finishedAt, progress: j.progress }))
69
+ .sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0))
70
+ .slice(0, JOB_LIMIT)
71
+ }
package/src/paths.js ADDED
@@ -0,0 +1,30 @@
1
+ import { readFileSync } from "node:fs"
2
+ import { createRequire } from "node:module"
3
+ import { homedir } from "node:os"
4
+ import { dirname, join } from "node:path"
5
+ import { fileURLToPath } from "node:url"
6
+
7
+ // Where things live: this package, the pinned DSH it launches, and the
8
+ // Kriya home (DSH_HOME for every profile it boots).
9
+
10
+ export const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..")
11
+
12
+ const require = createRequire(join(PACKAGE_ROOT, "package.json"))
13
+
14
+ export const PACKAGE = JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8"))
15
+
16
+ /** The client version sent as X-Kriya-Harness (plain x.y.z, as the contract requires). */
17
+ export const CLIENT_VERSION = PACKAGE.version
18
+
19
+ const DSH_PACKAGE = require.resolve("@deepseek-ai/dsh/package.json")
20
+
21
+ /** The pinned DSH version (exact, from its own package.json). */
22
+ export const DSH_VERSION = JSON.parse(readFileSync(DSH_PACKAGE, "utf8")).version
23
+
24
+ /** DSH's own launcher; booting stays DSH's ("only dsh profiles launch"). */
25
+ export const DSH_BIN = join(dirname(DSH_PACKAGE), "lib", "bin.js")
26
+
27
+ /** The Kriya home: KRIYA_HOME, else ~/.kriya. Read per call so tests can set it. */
28
+ export function kriyaHome() {
29
+ return process.env.KRIYA_HOME || join(homedir(), ".kriya")
30
+ }