@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/intent.js ADDED
@@ -0,0 +1,130 @@
1
+ // The intent router's brief (plugins/router; Kriya-Tavi
2
+ // docs/kriya-harness/INTENT_ROUTER_AND_LONG_HORIZON.md): from the person's
3
+ // request, by code, which skills of the live catalog are likely to help
4
+ // (BM25 over each skill's name, description and when-to-use) and which tools
5
+ // to start with (fixed intent classes, naming only tools this agent has).
6
+ // It hides nothing and adds no tool: a short hint the model may ignore, so a
7
+ // weak model starts with the right skill and the project's check instead of
8
+ // guessing. Deterministic: the same request and catalog give the same brief.
9
+
10
+ const STOP = new Set(
11
+ "a an and are as at be but by can could do does for from had has have how i if in into is it its me my of on or our please should so that the their them then there these this to us was we were what when where which who why will with would you your".split(" ")
12
+ )
13
+
14
+ /** Lower-case word stems: letters and digits, simple plural and -ing/-ed endings dropped */
15
+ export function tokens(text) {
16
+ return String(text ?? "")
17
+ .toLowerCase()
18
+ .split(/[^a-z0-9]+/)
19
+ .filter((w) => w.length > 1 && !STOP.has(w))
20
+ .map((w) => {
21
+ const base = w.replace(/(ies)$/, "y")
22
+ const stem = base.replace(/(ing|ed|es|s)$/, (m, _e, _i, str) => (str.length - m.length >= 3 ? "" : m))
23
+ // "debugging" → "debugg" → "debug", "running" → "run" (not "ll", "ss", "zz")
24
+ return stem !== base && /(ing|ed)$/.test(base) && /([b-df-hj-km-np-rtv-y])\1$/.test(stem) ? stem.slice(0, -1) : stem
25
+ })
26
+ }
27
+
28
+ /**
29
+ * BM25 over the catalog (k1 1.2, b 0.75). A skill's name parts count twice:
30
+ * a name is the most deliberate routing signal it has.
31
+ * @param {string} query
32
+ * @param {Array<{ name: string, description?: string, whenToUse?: string }>} skills
33
+ * @returns {Array<{ name: string, score: number }>} positive scores, best first, ties by name
34
+ */
35
+ export function rankSkills(query, skills) {
36
+ const q = [...new Set(tokens(query))]
37
+ if (!q.length || !skills.length) return []
38
+ const docs = skills.map((s) => {
39
+ const name = tokens(s.name.replace(/-/g, " "))
40
+ return [...name, ...name, ...tokens(s.description), ...tokens(s.whenToUse)]
41
+ })
42
+ const avg = docs.reduce((n, d) => n + d.length, 0) / docs.length || 1
43
+ const df = new Map(q.map((t) => [t, docs.filter((d) => d.includes(t)).length]))
44
+ const N = docs.length
45
+ return skills
46
+ .map((s, i) => {
47
+ const d = docs[i]
48
+ let score = 0
49
+ for (const t of q) {
50
+ const f = d.filter((w) => w === t).length
51
+ if (!f) continue
52
+ const idf = Math.log(1 + (N - df.get(t) + 0.5) / (df.get(t) + 0.5))
53
+ score += idf * ((f * 2.2) / (f + 1.2 * (1 - 0.75 + (0.75 * d.length) / avg)))
54
+ }
55
+ return { name: s.name, score: Math.round(score * 1000) / 1000 }
56
+ })
57
+ .filter((r) => r.score > 0)
58
+ .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name))
59
+ }
60
+
61
+ // Intent classes: words that signal them, and the tools to start with (each
62
+ // tool listed only if this agent has it), in the order to use them
63
+ export const INTENTS = [
64
+ { id: "fix", label: "fix a failure", words: ["bug", "error", "fail", "failing", "broken", "crash", "fix", "exception", "regression", "wrong", "doesn't", "not working", "issue"], tools: [["kriya_verify", "reproduce the failure first"], ["grep", "find where it happens"], ["read", "read the code"], ["edit", "fix the cause once"]], loop: "reproduce, find the cause, fix it once, re-run, check nothing else broke" },
65
+ { id: "build", label: "build something new", words: ["add", "build", "implement", "create", "feature", "support", "new", "make"], tools: [["kriya_plan", "plan it if it has several parts"], ["glob", "see how the project is laid out"], ["read", "follow the existing patterns"], ["write", "add files"], ["edit", "change files"]], loop: "build the smallest working part, run it, test it, repair, re-test" },
66
+ { id: "test", label: "tests", words: ["test", "tests", "coverage", "spec", "tdd", "unit"], tools: [["kriya_verify", "run the project's check"], ["read", "read the existing tests"]], loop: "write a test that fails for the right reason, make it pass, run them all" },
67
+ { id: "refactor", label: "restructure code", words: ["refactor", "rename", "clean", "simplify", "migrate", "move", "split", "extract", "reorganize"], tools: [["grep", "find every caller first"], ["kriya_plan", "plan it in checkable steps"], ["edit", "change files"]], loop: "change one thing, run the check, then the next" },
68
+ { id: "web", label: "a web page or UI", words: ["page", "ui", "button", "form", "css", "layout", "frontend", "browser", "localhost", "react", "component", "screen", "style", "html"], tools: [["browser_open", "open the running app"], ["browser_read", "see its text and elements"], ["browser_screenshot", "see its layout"], ["browser_console", "check for errors"]], loop: "render it, look at it, name what's wrong, fix that, look again; judge from the page, not the code" },
69
+ { id: "review", label: "review", words: ["review", "pr", "pull request", "diff", "audit", "check my"], tools: [["bash", "git diff to see the change"], ["read", "read the connected code"]] },
70
+ { id: "explain", label: "explain or find", words: ["explain", "what", "how", "why", "understand", "where", "find", "show", "describe", "overview"], tools: [["glob", "see the layout"], ["grep", "find the place"], ["read", "read it"]] },
71
+ { id: "research", label: "research", words: ["research", "investigate", "compare", "sources", "evidence", "survey"], tools: [["grep", "search what's here first"], ["read", "read the primary source"]], loop: "split the question, read primary sources, cross-check each claim, then write; mark what stayed unverified" },
72
+ { id: "data", label: "data analysis", words: ["analyze", "analyse", "dataset", "csv", "spreadsheet", "statistics", "aggregate"], tools: [["read", "inspect the data first"], ["bash", "compute, don't estimate"]], loop: "inspect the data, transform it, compute, sanity-check totals, then report" },
73
+ { id: "git", label: "git", words: ["commit", "branch", "push", "merge", "rebase", "git", "stash", "cherry-pick"], tools: [["bash", "git status first; ask before commit or push"]] },
74
+ { id: "security", label: "security", words: ["auth", "login", "password", "token", "secret", "injection", "xss", "csrf", "security", "permission", "vulnerab"], tools: [["grep", "find where untrusted input enters"], ["read", "follow it"]] },
75
+ ]
76
+
77
+ // A request about a shipped artifact rather than source: words only this kind of work uses
78
+ const REVERSE = /\b(reverse[- ]engineer\w*|decompil\w*|disassembl\w*|deobfuscat\w*|binary analysis|ghidra|frida|apk|ipa|asar|dylib|mach-?o|pcap|firmware (image|dump)|what does this (binary|app)|how does (this|the) (binary|electron app))\b|\.(exe|dll|so|wasm|elf)\b/i
79
+
80
+ /** Whether a request is reverse-engineering work (plugins/rea) */
81
+ export const isReverseEngineering = (request) => REVERSE.test(String(request ?? ""))
82
+
83
+ /** The request's intents, strongest first (at most two), by whole-word or phrase matches */
84
+ export function classify(request) {
85
+ const text = ` ${String(request ?? "").toLowerCase().replace(/\s+/g, " ")} `
86
+ return INTENTS.map((intent) => ({
87
+ intent,
88
+ // Short words whole (so "pr" isn't "print"); longer ones as word starts ("fail" in "failing")
89
+ score: intent.words.filter((w) => new RegExp(`[^a-z]${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}${w.length <= 3 ? "(?![a-z])" : ""}`).test(text)).length,
90
+ }))
91
+ .filter((r) => r.score > 0)
92
+ .sort((a, b) => b.score - a.score || INTENTS.indexOf(a.intent) - INTENTS.indexOf(b.intent))
93
+ .slice(0, 2)
94
+ .map((r) => r.intent)
95
+ }
96
+
97
+ const MAX_SKILLS = 4
98
+ export const MAX_BRIEF = 900
99
+ // A request this short, in one line, is rarely several parts
100
+ const SMALL = 160
101
+
102
+ /**
103
+ * The brief for one request, or "" when nothing is worth saying.
104
+ * @param {string} request the person's latest message
105
+ * @param {Array<{ name: string, description?: string, whenToUse?: string, invocation?: { modelInvocable?: boolean } }>} skills the live catalog
106
+ * @param {Iterable<string>} toolNames the tools this agent has
107
+ */
108
+ export function brief(request, skills, toolNames) {
109
+ const have = new Set(toolNames)
110
+ const usable = skills.filter((s) => s.invocation?.modelInvocable !== false)
111
+ const intents = classify(request)
112
+ // The intents' own words join the query, so "it crashes" finds debugging skills
113
+ const query = [request, ...intents.map((i) => i.label)].join(" ")
114
+ const picked = rankSkills(query, usable).slice(0, MAX_SKILLS).map((r) => r.name)
115
+ const seen = new Set()
116
+ const tools = intents
117
+ .flatMap((i) => i.tools)
118
+ .filter(([name]) => have.has(name) && !seen.has(name) && seen.add(name))
119
+ .slice(0, 5)
120
+ if (!picked.length && !tools.length) return ""
121
+ const lines = ["Routing for this request, chosen by Kriya Harness from its words (a hint, not a rule):"]
122
+ if (intents.length) lines.push(`Intent: ${intents.map((i) => i.label).join("; ")}.`)
123
+ if (intents[0]?.loop) lines.push(`Way of working: ${intents[0].loop}.`)
124
+ if (have.has("kriya_plan") && intents.length && request.length <= SMALL && !request.includes("\n")) lines.push("This reads as one small change: do it directly; kriya_plan is for several parts.")
125
+ if (picked.length) lines.push(`Skills likely to help: ${picked.join(", ")}.${have.has("skill") ? " Load the ones that fit with the skill tool before you start." : ""}`)
126
+ if (tools.length) lines.push(`Start with: ${tools.map(([name, why]) => `${name} (${why})`).join(", ")}.`)
127
+ if (have.has("kriya_verify") && intents.some((i) => ["fix", "build", "test", "refactor"].includes(i.id))) lines.push("Finish with kriya_verify: only its result says the work passes.")
128
+ const text = lines.join("\n")
129
+ return text.length > MAX_BRIEF ? `${text.slice(0, MAX_BRIEF - 1)}…` : text
130
+ }
package/src/launch.js ADDED
@@ -0,0 +1,315 @@
1
+ import { spawn, spawnSync } from "node:child_process"
2
+
3
+ import { broadcastRun } from "./daemon.js"
4
+ import { BODY_ENCODING, startGatewayProxy } from "./gateway-proxy.js"
5
+ import { BASE_PATH, models } from "./api.js"
6
+ import { DEFAULT_MODE, modeEnv } from "./modes.js"
7
+ import { CLIENT_VERSION, DSH_BIN, kriyaHome } from "./paths.js"
8
+ import { ensureProfile } from "./profiles.js"
9
+
10
+ // Booting stays DSH's: `node <pinned dsh>/lib/bin.js --profile <name> …` with
11
+ // the Kriya home as DSH_HOME. The Kriya rows read three launch variables:
12
+ // the gateway address, the client version for X-Kriya-Harness, and the
13
+ // device token. The token's name contains TOKEN, so DSH scrubs it from every
14
+ // shell the agent runs (dsh-subprocess SENSITIVE_ENV_PATTERN; tested).
15
+
16
+ export const TOKEN_ENV = "KRIYA_DEVICE_TOKEN"
17
+
18
+ // Kriya's tier aliases in the order a session starts on them. A free plan may
19
+ // allow only budget; starting on a tier the plan lacks fails every request
20
+ // with tier_not_allowed
21
+ export const START_TIERS = ["balanced", "budget", "escalation"]
22
+
23
+ /**
24
+ * The tiers the plan allows (GET /models), in START_TIERS order, and the
25
+ * one a session starts on. The model picker offers only these, so a tier
26
+ * the plan refuses (tier_not_allowed on every request) can't be chosen.
27
+ * When Kriya can't be asked, all of them: the gateway still refuses what
28
+ * the plan lacks, and a short outage mustn't leave the picker empty.
29
+ */
30
+ export async function planTiers(device, list = models) {
31
+ const all = { start: START_TIERS[0], allowed: [...START_TIERS], names: {}, limits: {}, images: [], encodings: [] }
32
+ if (!device) return all
33
+ try {
34
+ const answer = await list(device.url, device.token)
35
+ const data = answer.data
36
+ // The request-body forms Kriya decodes (src/gateway-proxy.js); none from an older Kriya
37
+ const encodings = Array.isArray(answer.bodyEncodings) ? answer.bodyEncodings.filter((e) => typeof e === "string") : []
38
+ const offered = new Set(data.map((model) => model.id))
39
+ const allowed = START_TIERS.filter((tier) => offered.has(tier))
40
+ return allowed.length ? { start: allowed[0], allowed, names: modelNames(data, allowed), limits: modelLimits(data, allowed), images: allowed.filter((tier) => data.find((m) => m.id === tier)?.images === true), encodings } : { ...all, encodings }
41
+ } catch {
42
+ // Kriya answers the first request with the reason if it's refused
43
+ return all
44
+ }
45
+ }
46
+
47
+ // The contract's own rule for a model name (contract/contract.json /models)
48
+ const MODEL_NAME = /^[\p{L}\p{N} .()+\/:_-]{1,60}$/u
49
+
50
+ /**
51
+ * What the picker shows per tier: the model the owner routes it to, as Kriya
52
+ * names it ("DeepSeek V4.1 Flash"), with the tier added where two tiers run
53
+ * on the same model. A tier without a usable name keeps "Kriya <tier>".
54
+ */
55
+ export function modelNames(data, allowed) {
56
+ const named = Object.fromEntries(
57
+ data.filter((m) => allowed.includes(m.id) && typeof m.name === "string" && MODEL_NAME.test(m.name)).map((m) => [m.id, m.name])
58
+ )
59
+ const count = (name) => Object.values(named).filter((n) => n === name).length
60
+ return Object.fromEntries(Object.entries(named).map(([tier, name]) => [tier, count(name) > 1 ? `${name} · ${tier}` : name]))
61
+ }
62
+
63
+ // DSH's own compaction headroom (dsh-compaction-basic headroomTokens)
64
+ const DSH_HEADROOM = 65536
65
+ // The most context a request may use: DSH's own default window. A model that
66
+ // holds more (the budget tier's holds 1,048,576) still compacts here, because
67
+ // cost grows with every token re-sent and quality falls on long contexts;
68
+ // raise it only when KriyaBench shows it pays (KU-ADR-09)
69
+ export const WORKING_WINDOW = 262144
70
+ const positive = (n) => Number.isSafeInteger(n) && n > 0
71
+
72
+ /**
73
+ * What each tier's model holds (harness upgrade U3), from GET /models:
74
+ * DSH then compacts before a smaller model's real window is full instead of
75
+ * assuming 262,144 tokens for every tier (never more than WORKING_WINDOW). The output cap is the gateway's
76
+ * (never above a quarter of the window) and the compaction headroom is a
77
+ * quarter of the window at most, so DSH's trigger W − O − headroom stays
78
+ * positive on small windows. A tier Kriya gives no limits for keeps DSH's
79
+ * defaults, exactly as before.
80
+ */
81
+ export function modelLimits(data, allowed) {
82
+ return Object.fromEntries(
83
+ data
84
+ .filter((m) => allowed.includes(m.id) && positive(m.contextWindow) && positive(m.maxOutputTokens))
85
+ .map((m) => {
86
+ const window = Math.min(m.contextWindow, WORKING_WINDOW)
87
+ const quarter = Math.floor(window / 4)
88
+ return [m.id, { contextWindow: window, maxTokens: Math.min(m.maxOutputTokens, quarter), headroomTokens: Math.min(DSH_HEADROOM, quarter) }]
89
+ })
90
+ )
91
+ }
92
+
93
+ /** The first of START_TIERS the plan allows; balanced when Kriya can't be asked. */
94
+ export async function startTier(device, list = models) {
95
+ return (await planTiers(device, list)).start
96
+ }
97
+
98
+ /** @param {{ url: string, token: string } | null} device */
99
+ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = []) {
100
+ const env = {
101
+ ...base,
102
+ // The mode always comes from `--mode` (or the default), never the shell
103
+ ...modeEnv(mode),
104
+ DSH_HOME: kriyaHome(),
105
+ // Telemetry exporters are disabled rows in the kriya bundle; this is DSH's own switch too
106
+ DSH_TELEMETRY_DISABLED: "1",
107
+ KRIYA_CLIENT_VERSION: CLIENT_VERSION,
108
+ KRIYA_START_TIER: START_TIERS.includes(tier) ? tier : START_TIERS[0],
109
+ // Read by the kriya provider row: the models the picker offers. Never from the shell
110
+ KRIYA_ALLOWED_TIERS: (allowed.filter((t) => START_TIERS.includes(t)).length ? allowed.filter((t) => START_TIERS.includes(t)) : START_TIERS).join(","),
111
+ // The picker's name per tier (modelNames), as JSON. Never from the shell
112
+ KRIYA_MODEL_NAMES: JSON.stringify(Object.fromEntries(Object.entries(names).filter(([t, n]) => START_TIERS.includes(t) && typeof n === "string" && n.length <= 80))),
113
+ // Each tier's context window, output cap and compaction headroom (modelLimits), as JSON. Never from the shell
114
+ KRIYA_MODEL_LIMITS: JSON.stringify(Object.fromEntries(Object.entries(limits).filter(([t]) => START_TIERS.includes(t)))),
115
+ // The tiers whose model takes images, as GET /models says. Never from the shell
116
+ KRIYA_MODEL_IMAGES: images.filter((t) => START_TIERS.includes(t)).join(","),
117
+ }
118
+ // A token from the person's environment never stands in for the sign-in
119
+ delete env[TOKEN_ENV]
120
+ delete env.KRIYA_GATEWAY_URL
121
+ if (device) {
122
+ env[TOKEN_ENV] = device.token
123
+ env.KRIYA_GATEWAY_URL = `${device.url}${BASE_PATH}`
124
+ }
125
+ return env
126
+ }
127
+
128
+ function args(profile, rest) {
129
+ return [DSH_BIN, "--profile", profile, ...rest]
130
+ }
131
+
132
+ // Kriya's refusals reach DSH's OpenAI-compatible route as `{ error: "<code>",
133
+ // message }`, which pi-ai reports as `PI_AI_ERROR: <status> "<code>"`, dropping
134
+ // the sentence. Until the gateway answers in OpenAI's error shape, `kriya run`
135
+ // adds the plain words for the contract's codes (shortcut: headless only; the
136
+ // Web UI still shows the code; upgrade by changing the gateway's error shape).
137
+ export const REFUSALS = {
138
+ cap_reached: "This month's Kriya Harness limit is reached. It resets on the 1st (India time), or raise it in your plan.",
139
+ plan_not_allowed: "Kriya Harness isn't part of your plan.",
140
+ context_length_exceeded: "The conversation grew past the model's context window and couldn't be compacted enough; start a new session or type /compact.",
141
+ tier_not_allowed: "That model tier isn't on your plan; choose another in the model picker, or restart kriya to see only your plan's tiers.",
142
+ harness_off: "Kriya Harness is switched off for now.",
143
+ rate_limited: "Too many requests; wait a minute and try again.",
144
+ upstream_unavailable: "Kriya's model provider isn't answering; try again shortly.",
145
+ not_priced: "Kriya can't price this request yet; try again later.",
146
+ unauthorized: "This device is signed out. Run kriya login.",
147
+ suspended: "This Kriya account is paused.",
148
+ upgrade: "Update Kriya Harness (npm install -g @kriya-ai/harness).",
149
+ not_found: "Kriya Harness isn't available on this Kriya address; check it with kriya doctor.",
150
+ bad_request: "Kriya couldn't read that request; update Kriya Harness and try again.",
151
+ server_error: "Something went wrong in Kriya; try again shortly.",
152
+ // H6: the mirror's refusals (the plugin handles them; listed for completeness)
153
+ no_agent: "Choose the agent this computer works as in Kriya, Account → Devices.",
154
+ mirror_summary_only: "This computer mirrors summaries only.",
155
+ // H8: handoff and pull (kriya handoff / kriya pull print Kriya's own sentence)
156
+ not_connected: "Connect GitHub in Kriya, Account → Apps, then hand off again.",
157
+ too_large: "The changes are larger than a handoff allows.",
158
+ patch_mismatch: "The upload was damaged on the way; hand off again.",
159
+ no_checkpoint: "This workspace has no changes saved yet.",
160
+ task_refused: "Kriya couldn't start the task for this handoff; try again shortly.",
161
+ }
162
+
163
+ const PI_AI_ERROR = /PI_AI_ERROR: \d{3} "([a-z_]+)"/
164
+
165
+ /** The plain sentence for a DSH error line naming a Kriya refusal, if any. */
166
+ export function explain(line) {
167
+ const code = PI_AI_ERROR.exec(line)?.[1]
168
+ return code && Object.hasOwn(REFUSALS, code) ? REFUSALS[code] : null
169
+ }
170
+
171
+ const HTML_ERROR = /^dsh: \w+: (\d{3}) <(!DOCTYPE|html)/i
172
+
173
+ /**
174
+ * Passes DSH's stderr through line by line, except a web page as an error
175
+ * body: when Kriya's host answers with its own error page (a deploy, an
176
+ * outage), DSH prints the whole HTML. That page is dropped and `explained`
177
+ * says what happened instead.
178
+ * @param {(text: string) => void} write
179
+ */
180
+ export function htmlFilter(write) {
181
+ let partial = ""
182
+ let inPage = false
183
+ const state = {
184
+ /** @type {string | null} */
185
+ explained: null,
186
+ push(text) {
187
+ const lines = (partial + text).split("\n")
188
+ partial = lines.pop() ?? ""
189
+ for (const line of lines) {
190
+ if (inPage) {
191
+ if (/<\/html>/i.test(line)) inPage = false
192
+ continue
193
+ }
194
+ const page = HTML_ERROR.exec(line)
195
+ if (page) {
196
+ inPage = !/<\/html>/i.test(line)
197
+ state.explained = `Kriya didn't answer (HTTP ${page[1]}); it may be restarting. Changes made so far stay in this folder; try again in a minute.`
198
+ continue
199
+ }
200
+ write(`${line}\n`)
201
+ }
202
+ },
203
+ end() {
204
+ if (partial && !inPage) write(partial)
205
+ partial = ""
206
+ },
207
+ }
208
+ return state
209
+ }
210
+
211
+ /**
212
+ * DSH's own terminal lines in Kriya Harness's words (owner, 2026-11-06): the
213
+ * product people run is Kriya Harness; DSH stays credited in --version and
214
+ * the notices. Only a line's leading "dsh web:" / "dsh:" changes.
215
+ */
216
+ export function rebrand(text) {
217
+ return text
218
+ .replace(/^dsh web: opening the default browser; pass --no-open to disable/, "Kriya Harness: opening your browser (kriya --no-open to skip)")
219
+ .replace(/^dsh web: /, "Kriya Harness: ")
220
+ .replace(/^dsh: /, "kriya: ")
221
+ }
222
+
223
+ /** Writes a stream's text through `rebrand`, whole lines at a time */
224
+ function relines(stream, write) {
225
+ let partial = ""
226
+ stream.setEncoding("utf8")
227
+ stream.on("data", (chunk) => {
228
+ const lines = (partial + chunk).split("\n")
229
+ partial = lines.pop() ?? ""
230
+ for (const line of lines) write(`${rebrand(line)}\n`)
231
+ })
232
+ stream.on("end", () => partial && write(rebrand(partial)))
233
+ }
234
+
235
+ /** Runs DSH in the foreground, passing the terminal through; resolves with its exit code. */
236
+ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
237
+ ensureProfile(profile)
238
+ const headless = profile === "kriya-run"
239
+ const tiers = await planTiers(device)
240
+ // DSH and the Kriya plugins reach Kriya through the local relay
241
+ // (src/gateway-proxy.js): encoded bodies past the host's firewall, and a
242
+ // block said as such. KRIYA_RELAY=off talks to Kriya directly, as before
243
+ const relay =
244
+ device && process.env.KRIYA_RELAY !== "off"
245
+ ? await startGatewayProxy({
246
+ target: device.url,
247
+ encode: tiers.encodings.includes(BODY_ENCODING),
248
+ // A Kriya deployed after launch is picked up without a restart
249
+ checkSupport: async () => ((await models(device.url, device.token)).bodyEncodings ?? []).includes(BODY_ENCODING),
250
+ log: (text) => process.stderr.write(`kriya: ${text}\n`),
251
+ })
252
+ : null
253
+ // What this process runs, for Kriya's Control Center (no task text; nothing on a Kriya without it)
254
+ const on = (name) => process.env[name] === "on"
255
+ const broadcast = broadcastRun(device, {
256
+ kind: profile === "kriya-run" ? "run" : profile === "kriya-acp" ? "acp" : "app",
257
+ mode,
258
+ switches: { loop: on("KRIYA_LOOP"), loopV2: on("KRIYA_LOOP_V2"), budget: on("KRIYA_BUDGET"), anchor: on("KRIYA_ANCHOR"), browser: on("KRIYA_BROWSER") },
259
+ })
260
+ return new Promise((done, fail) => {
261
+ const child = spawn(process.execPath, args(profile, rest), {
262
+ // stdout: the answer (kriya run) and ACP's protocol frames pass untouched;
263
+ // the Web UI's stdout carries only log lines, rebranded like stderr
264
+ stdio: ["inherit", profile === "kriya" ? "pipe" : "inherit", "pipe"],
265
+ env: launchEnv(relay ? { ...device, url: relay.url } : device, process.env, mode, tiers.start, tiers.allowed, tiers.names, tiers.limits, tiers.images),
266
+ })
267
+ let explained = null
268
+ const filter = htmlFilter((text) => process.stderr.write(rebrand(text)))
269
+ if (child.stdout) relines(child.stdout, (text) => process.stdout.write(text))
270
+ if (!headless) relines(child.stderr, (text) => process.stderr.write(text))
271
+ if (headless) {
272
+ let buffered = ""
273
+ // Whole characters per chunk, so a split one never reaches the filter
274
+ child.stderr.setEncoding("utf8")
275
+ child.stderr.on("data", (chunk) => {
276
+ filter.push(chunk)
277
+ buffered = (buffered + chunk).slice(-4096)
278
+ explained ??= explain(buffered) ?? filter.explained
279
+ })
280
+ }
281
+ // Ctrl-C reaches the child directly (same process group): forwarding it
282
+ // too would be a second interrupt, which DSH treats as force-exit. A
283
+ // SIGTERM or SIGHUP sent to kriya alone is passed on, or DSH would outlive it
284
+ process.on("SIGINT", () => {})
285
+ for (const signal of ["SIGTERM", "SIGHUP"]) process.on(signal, () => child.kill(signal))
286
+ child.on("error", (error) => {
287
+ relay?.close()
288
+ fail(error)
289
+ })
290
+ // close, not exit: stderr may still hold the last lines when DSH exits
291
+ child.on("close", (code, signal) => {
292
+ relay?.close()
293
+ // Kriya hears how it ended before kriya exits (each request is capped at 5 s)
294
+ const ended = broadcast.end(code === 0 ? "completed" : signal ? "stopped" : "failed", code ?? undefined)
295
+ filter.end()
296
+ explained ??= filter.explained
297
+ if (explained) process.stderr.write(`kriya: ${explained}\n`)
298
+ ended.finally(() => done(code ?? (signal ? 1 : 0)))
299
+ })
300
+ })
301
+ }
302
+
303
+ /** Composes a profile without booting it (`--dump-config`); returns the YAML. */
304
+ export function dumpConfig(profile, device = null, mode = DEFAULT_MODE) {
305
+ ensureProfile(profile)
306
+ const result = spawnSync(process.execPath, args(profile, ["--dump-config"]), {
307
+ env: launchEnv(device, process.env, mode),
308
+ encoding: "utf8",
309
+ maxBuffer: 32 * 1024 * 1024,
310
+ })
311
+ if (result.status !== 0) {
312
+ throw new Error(`dsh --dump-config failed for ${profile}: ${(result.stderr || "").trim().slice(0, 500)}`)
313
+ }
314
+ return result.stdout
315
+ }
package/src/live.js ADDED
@@ -0,0 +1,81 @@
1
+ // Remote Control's stream (Kriya-Tavi docs/kriya-harness/REMOTE_CONTROL.md):
2
+ // DSH's committed session events as the short lines Kriya shows. A tool line
3
+ // carries one target (a path, a command, an address), never its output.
4
+
5
+ export const MAX_TEXT = 8000
6
+ const MAX_TARGET = 400
7
+
8
+ const cut = (text, max) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`)
9
+
10
+ const textOf = (content) =>
11
+ (Array.isArray(content) ? content : [])
12
+ .filter((block) => block?.type === "text")
13
+ .map((block) => block.text)
14
+ .join("")
15
+
16
+ /** A command or address with anything secret-looking hidden */
17
+ export const redact = (text) =>
18
+ String(text)
19
+ .replace(/\b(bearer|basic)\s+[\w.~+/=-]+/gi, "$1 ***")
20
+ .replace(/([\w-]*(?:token|secret|password|passwd|pwd|api[_-]?key|auth)[\w-]*["']?\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi, "$1***")
21
+ .replace(/(--[\w-]*(?:token|secret|password|key)[\w-]*[ =])\S+/gi, "$1***")
22
+ .replace(/(\/\/[^/\s:@]+:)[^/\s@]+@/g, "$1***@")
23
+
24
+ const TARGET_KEYS = ["path", "file_path", "filePath", "url", "command", "pattern", "query", "ref", "description"]
25
+
26
+ /** The one thing a tool call acts on, from its JSON arguments */
27
+ export function targetOf(args) {
28
+ let value = args
29
+ try {
30
+ if (typeof args === "string") value = JSON.parse(args)
31
+ } catch {
32
+ return undefined
33
+ }
34
+ const key = TARGET_KEYS.find((name) => typeof value?.[name] === "string" && value[name])
35
+ return key ? cut(redact(value[key]), MAX_TARGET) : undefined
36
+ }
37
+
38
+ /**
39
+ * One DSH session event as a change to the stream.
40
+ * @param {{ type: string, time: number, data: any }} event
41
+ * @param {Map<string, { time: number }>} calls the open tool calls
42
+ * @returns {{ line?: object, state?: string, title?: string } | null}
43
+ */
44
+ export function liveChange(event, calls) {
45
+ const { type, data, time } = event
46
+ switch (type) {
47
+ case "turn/start":
48
+ case "approval/decided":
49
+ return { state: "running" }
50
+ case "turn/end":
51
+ return { state: "idle" }
52
+ case "approval/asked":
53
+ return { state: "waiting" }
54
+ case "user/message": {
55
+ if (data?.source?.kind !== "user") return null
56
+ const text = textOf(data.content).trim()
57
+ return text ? { state: "running", title: cut(text.split("\n")[0], 120), line: { kind: "user", text: cut(text, MAX_TEXT) } } : null
58
+ }
59
+ case "assistant/message": {
60
+ const text = textOf(data?.message?.content).trim()
61
+ return text ? { line: { kind: "assistant", text: cut(text, MAX_TEXT) } } : null
62
+ }
63
+ case "tool/call": {
64
+ calls.set(data.callId, { time })
65
+ const target = targetOf(data.arguments)
66
+ // Also tells a session switched on mid-turn that it's working
67
+ return { state: "running", line: { kind: "tool_start", callId: String(data.callId).slice(0, 100), tool: cut(String(data.name), 60), ...(target && { target }) } }
68
+ }
69
+ case "tool/result": {
70
+ const id = data.message?.toolCallId
71
+ const started = calls.get(id)
72
+ if (!started) return null
73
+ calls.delete(id)
74
+ const failed = data.message.isError || data.error
75
+ const declined = failed && /the user rejected (tool|escalating)/.test(textOf(data.message.content))
76
+ return { line: { kind: "tool_end", callId: String(id).slice(0, 100), status: declined ? "declined" : failed ? "error" : "ok", ms: Math.max(0, Math.round(time - started.time)) } }
77
+ }
78
+ default:
79
+ return null
80
+ }
81
+ }