@kriya-ai/harness 0.2.5 → 2.0.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 (132) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +49 -0
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +498 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +376 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +426 -0
  33. package/plugins/runstrip/index.js +301 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +65 -6
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +169 -2
  44. package/src/edit/core/plan.js +65 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/type-kit.js +173 -0
  51. package/src/edit/director/ask.js +37 -3
  52. package/src/edit/director/assembly.js +829 -0
  53. package/src/edit/director/continuity.js +9 -1
  54. package/src/edit/director/custom-motion.js +88 -0
  55. package/src/edit/director/graphics.js +44 -10
  56. package/src/edit/director/intent.js +125 -0
  57. package/src/edit/director/mentions.js +52 -0
  58. package/src/edit/director/plan.js +43 -11
  59. package/src/edit/director/revise.js +132 -9
  60. package/src/edit/director/viewer.js +136 -0
  61. package/src/edit/director/watch-fix.js +119 -0
  62. package/src/edit/engine/captions.js +110 -5
  63. package/src/edit/engine/confine.js +81 -4
  64. package/src/edit/engine/custom.js +243 -0
  65. package/src/edit/engine/dna2.js +893 -0
  66. package/src/edit/engine/fonts.js +218 -0
  67. package/src/edit/engine/graphics.js +271 -10
  68. package/src/edit/engine/index.js +14 -5
  69. package/src/edit/engine/motion.js +148 -13
  70. package/src/edit/engine/music-bed.js +59 -1
  71. package/src/edit/engine/packs.js +11 -0
  72. package/src/edit/engine/reference2.js +26 -0
  73. package/src/edit/engine/sfx.js +56 -1
  74. package/src/edit/engine/tool.js +21 -5
  75. package/src/edit/gates/assembly.js +194 -0
  76. package/src/edit/gates/copy.js +7 -4
  77. package/src/edit/gates/index.js +72 -7
  78. package/src/edit/gates/reference.js +115 -0
  79. package/src/edit/gates/tile.js +96 -0
  80. package/src/edit/host/client.js +4 -3
  81. package/src/edit/host/clips.js +33 -0
  82. package/src/edit/host/jobs.js +9 -3
  83. package/src/edit/host/layers.js +134 -0
  84. package/src/edit/host/main.js +10 -3
  85. package/src/edit/host/paths.js +21 -3
  86. package/src/edit/host/preview.js +108 -0
  87. package/src/edit/host/projects.js +443 -34
  88. package/src/edit/host/server.js +235 -20
  89. package/src/edit/host/tavi.js +77 -0
  90. package/src/edit/loop/make.js +28 -3
  91. package/src/edit/recipes/assembly.js +352 -0
  92. package/src/edit/recipes/graphic-clips.js +4 -2
  93. package/src/edit/recipes/openings.js +36 -0
  94. package/src/edit/recipes/reel.js +104 -14
  95. package/src/edit/recipes/reference-look.js +29 -0
  96. package/src/edit/recipes/short-from-long.js +3 -3
  97. package/src/edit/recipes/sound.js +71 -0
  98. package/src/edit/runtime/cli.js +26 -5
  99. package/src/edit/runtime/fetch.js +4 -4
  100. package/src/edit/runtime/licences.js +7 -1
  101. package/src/explore.js +103 -0
  102. package/src/failure.js +1 -1
  103. package/src/gate-commands.js +114 -0
  104. package/src/gates/api.js +127 -0
  105. package/src/gates/commands.js +111 -0
  106. package/src/gates/detectors.js +370 -0
  107. package/src/gates/http.js +62 -0
  108. package/src/gates/index.js +196 -0
  109. package/src/gates/page.js +264 -0
  110. package/src/gates/sast.js +64 -0
  111. package/src/gates/stack.js +110 -0
  112. package/src/gates/tenant.js +162 -0
  113. package/src/gates/three.js +407 -0
  114. package/src/gates/ui.js +111 -0
  115. package/src/launch.js +15 -3
  116. package/src/loop.js +199 -7
  117. package/src/mcp.js +126 -0
  118. package/src/milestones.js +188 -0
  119. package/src/modes.js +32 -0
  120. package/src/orchestra.js +43 -0
  121. package/src/outcomes.js +88 -0
  122. package/src/profiles.js +5 -0
  123. package/src/receipts.js +238 -0
  124. package/src/release.js +356 -0
  125. package/src/runstrip.js +122 -0
  126. package/src/stack.js +120 -0
  127. package/src/verify.js +67 -20
  128. package/studio/dist/fonts/fraunces.woff2 +0 -0
  129. package/studio/dist/fonts/geist.woff2 +0 -0
  130. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  131. package/studio/dist/studio.css +449 -1
  132. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,111 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { CONTRACTS_DIR } from "../contracts.js"
6
+ import { kriyaHome } from "../paths.js"
7
+ import { readStack } from "../stack.js"
8
+ import { keepShot, SCHEMES, VIEWPORTS, withGateBrowser } from "./page.js"
9
+
10
+ // Harness 2.0 W4: G-UI and G-A11Y (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
11
+ // GATES.md §3). Both read the same rendered pages, so they share one visit per
12
+ // route × viewport × scheme, made once per verify. The app is the one the
13
+ // person confirmed with `kriya stack use --app`; routes are "/" plus the
14
+ // component previews named in .kriya/contracts/component_states.json.
15
+
16
+ export const MAX_ROUTES = 4
17
+ export const CLS_LIMIT = 0.1
18
+ export const TARGET_MIN = 24
19
+ export const TARGET_WARN = 44
20
+
21
+ /** The routes to render: "/" and each component preview (contract, hash-locked by its owner), at most MAX_ROUTES. */
22
+ export function uiRoutes(root) {
23
+ const routes = ["/"]
24
+ const file = join(root, CONTRACTS_DIR, "component_states.json")
25
+ if (existsSync(file)) {
26
+ try {
27
+ for (const c of Object.values(JSON.parse(readFileSync(file, "utf8")))) if (typeof c?.preview === "string" && /^\/\S*$/.test(c.preview) && !routes.includes(c.preview)) routes.push(c.preview)
28
+ } catch {
29
+ // G-CONTRACT reports a broken contract
30
+ }
31
+ }
32
+ return routes.slice(0, MAX_ROUTES)
33
+ }
34
+
35
+ const evidenceDir = (root, label) =>
36
+ join(kriyaHome(), "evidence", createHash("sha256").update(root).digest("hex").slice(0, 16), String(label).replace(/[^\w.-]+/g, "-").slice(0, 60), new Date().toISOString().replace(/[:.]/g, "-"))
37
+
38
+ /**
39
+ * Every page report for this verify, or { skip: reason }. Made once and shared by G-UI and G-A11Y.
40
+ * @param {{ root: string, label: string, launch?: () => Promise<any> }} input
41
+ */
42
+ export async function uiReports({ root, label, launch, app: given }) {
43
+ // Harness 2.0 W17: G-RELEASE points the same visits at the production server it was given
44
+ const app = given ?? readStack(root).app
45
+ if (!app) return { skip: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)", optional: true }
46
+ const routes = uiRoutes(root)
47
+ const dir = evidenceDir(root, label)
48
+ const visited = await withGateBrowser(
49
+ async (open) => {
50
+ const reports = []
51
+ for (const route of routes)
52
+ for (const viewport of VIEWPORTS)
53
+ for (const scheme of SCHEMES) {
54
+ const report = await open(new URL(route, app).href, { viewport, scheme })
55
+ if (report.unreachable) return { unreachable: `${app} doesn't answer (${report.unreachable}); start the app, or confirm another with kriya stack use --app` }
56
+ const sha = keepShot(dir, `${route.replace(/\W+/g, "_") || "root"}-${viewport.name}-${scheme}.png`, report.shot)
57
+ delete report.shot
58
+ reports.push({ route, ...report, ...(sha && { evidence: sha }) })
59
+ }
60
+ return { reports }
61
+ },
62
+ { launch }
63
+ )
64
+ if (visited.unavailable) return { skip: visited.unavailable }
65
+ if (visited.value.unreachable) return { skip: visited.value.unreachable }
66
+ return { reports: visited.value.reports, dir }
67
+ }
68
+
69
+ const at = (r) => `${r.route} at ${r.viewport}px ${r.scheme}`
70
+ const lines = (items, n = 12) => items.slice(0, n).map((x) => `- ${x}`).join("\n") + (items.length > n ? `\n- … and ${items.length - n} more` : "")
71
+
72
+ /** G-UI over the shared reports */
73
+ export function judgeUi(ui) {
74
+ if (ui.skip) return { id: "G-UI", status: "not_checked", reason: ui.skip, ...(ui.optional && { optional: true }) }
75
+ const problems = []
76
+ const warnings = []
77
+ for (const r of ui.reports) {
78
+ for (const e of r.consoleErrors) problems.push(`${at(r)}: console error: ${e}`)
79
+ for (const f of r.failed) problems.push(`${at(r)}: request ${f}`)
80
+ if (r.status !== null && r.status >= 400) problems.push(`${at(r)}: the page answered ${r.status}`)
81
+ if (r.overflow) problems.push(`${at(r)}: the page scrolls sideways (content wider than the screen)`)
82
+ if (r.cls > CLS_LIMIT) problems.push(`${at(r)}: layout shift ${r.cls} (over ${CLS_LIMIT})`)
83
+ if (Number(r.viewport) < 768) {
84
+ for (const s of r.small) {
85
+ if (Math.min(...s.size) < TARGET_MIN) problems.push(`${at(r)}: ${s.what} is ${s.size.join("×")} px, under the ${TARGET_MIN} px minimum to tap`)
86
+ else if (Math.min(...s.size) < TARGET_WARN) warnings.push(`${at(r)}: ${s.what} is ${s.size.join("×")} px; ${TARGET_WARN} px is easier to tap`)
87
+ }
88
+ }
89
+ }
90
+ const unique = [...new Set(problems)]
91
+ const evidence = ui.reports.map((r) => r.evidence).filter(Boolean)
92
+ if (unique.length) return { id: "G-UI", status: "fail", kind: "gate", excerpt: `G-UI (rendered at ${VIEWPORTS.map((v) => v.name).join(", ")} px, light and dark):\n${lines(unique)}`, evidence }
93
+ return { id: "G-UI", status: "pass", evidence, ...(warnings.length && { warnings: warnings.length, note: lines([...new Set(warnings)], 6) }) }
94
+ }
95
+
96
+ /** G-A11Y over the shared reports: names, language, contrast (plain and over glass), heading order as a warning */
97
+ export function judgeA11y(ui) {
98
+ if (ui.skip) return { id: "G-A11Y", status: "not_checked", reason: ui.skip, ...(ui.optional && { optional: true }) }
99
+ const problems = []
100
+ const warnings = []
101
+ for (const r of ui.reports) {
102
+ if (!r.lang) problems.push(`${at(r)}: <html> has no lang`)
103
+ for (const u of r.unnamed) problems.push(`${at(r)}: ${u} has no accessible name`)
104
+ for (const c of r.lowContrast) problems.push(`${at(r)}: "${c.text}" (${c.what}) has contrast ${c.ratio}:1, needs ${c.need}:1`)
105
+ for (const g of r.glass) if (g.worst < g.need) problems.push(`${at(r)}: text on a glass surface (${g.what}) reaches only ${Math.round(g.worst * 100) / 100}:1 over its backdrop, needs ${g.need}:1; make the surface more opaque or add a solid fallback`)
106
+ if (r.headingSkips) warnings.push(`${at(r)}: heading levels skip ${r.headingSkips} time(s)`)
107
+ }
108
+ const unique = [...new Set(problems)]
109
+ if (unique.length) return { id: "G-A11Y", status: "fail", kind: "gate", excerpt: `G-A11Y:\n${lines(unique)}` }
110
+ return { id: "G-A11Y", status: "pass", ...(warnings.length && { warnings: warnings.length, note: lines([...new Set(warnings)], 6) }) }
111
+ }
package/src/launch.js CHANGED
@@ -37,7 +37,10 @@ export async function planTiers(device, list = models) {
37
37
  const encodings = Array.isArray(answer.bodyEncodings) ? answer.bodyEncodings.filter((e) => typeof e === "string") : []
38
38
  const offered = new Set(data.map((model) => model.id))
39
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 }
40
+ // Harness 2.0 W2: the owner's head and worker levels, only if both are offered and differ
41
+ const o = answer.orchestra
42
+ const orchestra = o && allowed.includes(o.head) && allowed.includes(o.worker) && o.head !== o.worker ? { head: o.head, worker: o.worker } : undefined
43
+ 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, ...(orchestra && { orchestra }) } : { ...all, encodings }
41
44
  } catch {
42
45
  // Kriya answers the first request with the reason if it's refused
43
46
  return all
@@ -96,7 +99,7 @@ export async function startTier(device, list = models) {
96
99
  }
97
100
 
98
101
  /** @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 = []) {
102
+ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = [], orchestra) {
100
103
  const env = {
101
104
  ...base,
102
105
  // The mode always comes from `--mode` (or the default), never the shell
@@ -115,6 +118,13 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
115
118
  // The tiers whose model takes images, as GET /models says. Never from the shell
116
119
  KRIYA_MODEL_IMAGES: images.filter((t) => START_TIERS.includes(t)).join(","),
117
120
  }
121
+ // Harness 2.0 W2: the head and worker levels come only from Kriya's GET /models, never the shell
122
+ delete env.KRIYA_ORCHESTRA_HEAD
123
+ delete env.KRIYA_ORCHESTRA_WORKER
124
+ if (orchestra && START_TIERS.includes(orchestra.head) && START_TIERS.includes(orchestra.worker)) {
125
+ env.KRIYA_ORCHESTRA_HEAD = orchestra.head
126
+ env.KRIYA_ORCHESTRA_WORKER = orchestra.worker
127
+ }
118
128
  // A token from the person's environment never stands in for the sign-in
119
129
  delete env[TOKEN_ENV]
120
130
  delete env.KRIYA_GATEWAY_URL
@@ -237,6 +247,8 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
237
247
  ensureProfile(profile)
238
248
  const headless = profile === "kriya-run"
239
249
  const tiers = await planTiers(device)
250
+ // Harness 2.0 W2: with --orchestra and Kriya's offer, the session itself runs on the head level
251
+ const orchestra = process.env.KRIYA_ORCHESTRA === "on" && process.env.KRIYA_LOOP === "on" ? tiers.orchestra : undefined
240
252
  // DSH and the Kriya plugins reach Kriya through the local relay
241
253
  // (src/gateway-proxy.js): encoded bodies past the host's firewall, and a
242
254
  // block said as such. KRIYA_RELAY=off talks to Kriya directly, as before
@@ -262,7 +274,7 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
262
274
  // stdout: the answer (kriya run) and ACP's protocol frames pass untouched;
263
275
  // the Web UI's stdout carries only log lines, rebranded like stderr
264
276
  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),
277
+ env: launchEnv(relay ? { ...device, url: relay.url } : device, process.env, mode, orchestra ? orchestra.head : tiers.start, tiers.allowed, tiers.names, tiers.limits, tiers.images, orchestra),
266
278
  })
267
279
  let explained = null
268
280
  const filter = htmlFilter((text) => process.stderr.write(rebrand(text)))
package/src/loop.js CHANGED
@@ -5,6 +5,9 @@ import { checkPremortem } from "./sentinel.js"
5
5
  import { PLAN_LIMITS, taskKind, TASK_KINDS } from "./strict.js"
6
6
  import { confirmCheck, markStalled, MAX_ATTEMPTS, readProgress, stepLabel, trimOutput, verdict, VerifyError, writeProgress } from "./verify.js"
7
7
  import { projectRoot } from "./skill-switches.js"
8
+ import { cartridgeSection } from "./cartridges.js"
9
+ import { polishSection } from "./critic.js"
10
+ import { directionHints, EXPLORE_ROLES, MAX_TAKES, MIN_TAKES, takeSection } from "./explore.js"
8
11
 
9
12
  // The Kriya loop's plan and steps (H14c; KRIYA_LOOP.md in the Kriya
10
13
  // repository). The task is split into at most MAX_STEPS ordered steps
@@ -71,7 +74,7 @@ function dependencies(value, n) {
71
74
  * can only add to what must hold; it can't replace the person's check.
72
75
  * @returns {{ goal: string, steps: Array<{ title: string, doneWhen: string, files: string[], after?: number[] }>, kind?: string, invariants?: string[], acceptance?: string[] }}
73
76
  */
74
- export function validatePlan(input, { v2 = false, strict = false, defensive = false } = {}) {
77
+ export function validatePlan(input, { v2 = false, strict = false, defensive = false, roles, contracts: contractNames, specTests = false, explore = false } = {}) {
75
78
  const goal = clean(input?.goal, GOAL)
76
79
  if (!goal) throw new VerifyError("A plan needs a goal: one sentence on what the task is for.")
77
80
  const steps = Array.isArray(input?.steps) ? input.steps : []
@@ -83,8 +86,34 @@ export function validatePlan(input, { v2 = false, strict = false, defensive = fa
83
86
  if (!title) throw new VerifyError(`Step ${i + 1} needs a title.`)
84
87
  if (!doneWhen) throw new VerifyError(`Step ${i + 1} needs done_when: what is true when it's finished.`)
85
88
  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) }) }
89
+ // Harness 2.0 cartridges: an optional role from Kriya's list; without `roles`, never read
90
+ const role = roles && step?.role !== undefined && step?.role !== null && step?.role !== "" ? String(step.role) : undefined
91
+ if (role && !roles.includes(role)) throw new VerifyError(`Step ${i + 1}'s role is one of: ${roles.join(", ")}; or leave it out.`)
92
+ // Harness 2.0 gates: the contract slices this step builds to ("api#/paths/~1orders"); without the option, never read
93
+ let contracts
94
+ if (contractNames && Array.isArray(step?.contracts) && step.contracts.length) {
95
+ contracts = step.contracts.map((c) => String(c).trim()).filter(Boolean).slice(0, 8)
96
+ const bad = contracts.find((c) => !contractNames.includes(c.split("#")[0]) || (c.includes("#") && !/^[a-z_]+#\/\S*$/.test(c)))
97
+ if (bad) throw new VerifyError(`Step ${i + 1}'s contract "${bad}" isn't one of ${contractNames.join(", ")}, optionally with #/a/json/pointer.`)
98
+ }
99
+ // Harness 2.0 W5: a spec-test step (judged red, ORCHESTRA §7); without the option, never read
100
+ const spec = specTests && step?.spec_tests === true
101
+ // Harness 2.0 W14 (WD-18): 2 or 3 takes of a creative step; without the option, never read
102
+ let takes
103
+ if (explore && step?.explore !== undefined && step?.explore !== null && step?.explore !== 0) {
104
+ takes = Number(step.explore)
105
+ if (!Number.isInteger(takes) || takes < MIN_TAKES || takes > MAX_TAKES) throw new VerifyError(`Step ${i + 1}'s explore is ${MIN_TAKES} or ${MAX_TAKES} takes; or leave it out.`)
106
+ if (!EXPLORE_ROLES.includes(role)) throw new VerifyError(`Step ${i + 1} explores only with role ${EXPLORE_ROLES.join(", ")}: takes are for creative work.`)
107
+ }
108
+ return { title, doneWhen, files, ...(v2 && { after: dependencies(step?.after, i + 1) }), ...(role && { role }), ...(contracts?.length && { contracts }), ...(spec && { specTests: true }), ...(takes && { explore: takes }) }
87
109
  })
110
+ // A spec step writes tests from the contracts and criteria before the code exists: nothing that
111
+ // builds the code may come before it
112
+ const first = out.findIndex((s) => s.specTests)
113
+ if (first !== -1) {
114
+ const early = out.slice(0, first).find((s) => s.role && IMPLEMENTING.has(s.role))
115
+ if (early) throw new VerifyError(`Step ${first + 1} writes spec tests, so it comes before the code they test; "${early.title}" (${early.role}) builds code and is listed first. Put the spec step right after the contracts.`)
116
+ }
88
117
  const titles = new Set(out.map((s) => s.title.toLowerCase()))
89
118
  if (titles.size !== out.length) throw new VerifyError("Two steps have the same title; each step is one distinct piece of work.")
90
119
  const { premortem, problem } = defensive ? checkPremortem(input?.premortem, out.length) : {}
@@ -103,6 +132,9 @@ function contract(input, goal, steps) {
103
132
 
104
133
  export { stepLabel }
105
134
 
135
+ /** Roles whose steps build the code a spec step's tests are about (Harness 2.0) */
136
+ export const IMPLEMENTING = new Set(["frontend", "backend", "fullstack", "mobile", "game", "devops", "cloud", "systems", "data", "ml"])
137
+
106
138
  /**
107
139
  * Saves the session's plan beside its runs. A new plan starts its steps
108
140
  * over; the earlier plans and runs are kept, and at most MAX_PLANS are made.
@@ -207,9 +239,13 @@ export function loopStateText(cwd, sessionId) {
207
239
  }
208
240
 
209
241
  /** 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 = [] } = {}) {
242
+ export function builderPrompt(plan, n, previous, rules = [], { limits = builderLimits(), checked = true, briefing = [], cartridge, slices, polish } = {}) {
211
243
  const step = plan.steps[n - 1]
212
244
  const lines = [
245
+ // Harness 2.0: the role's cartridge first and byte-stable, so a cached prefix holds across builders
246
+ ...(cartridge ? cartridgeSection(cartridge.name, cartridge.body) : []),
247
+ // Harness 2.0 contract bus: this step's slices, stable for all its attempts
248
+ ...(slices ? ["Contracts for this step. Build to them as written; only the role that owns a contract changes it, and the harness fails a step that changes one it doesn't own.", "", slices, "", "---", ""] : []),
213
249
  `You are building one step of a larger task. Do only this step, then stop.`,
214
250
  "",
215
251
  `Goal of the task: ${plan.goal}`,
@@ -255,6 +291,8 @@ export function builderPrompt(plan, n, previous, rules = [], { limits = builderL
255
291
  if (previous?.kind === "tests changed")
256
292
  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
293
  if (previous?.note) lines.push(previous.note)
294
+ // Harness 2.0 W6: one polish attempt after a pass, with the critic's major defects
295
+ if (polish?.length) lines.push(...polishSection(polish))
258
296
  return lines.join("\n")
259
297
  }
260
298
 
@@ -309,7 +347,7 @@ const textOf = (blocks) =>
309
347
  * undo --list`. Nothing but Kriya's own restore touches the person's git.
310
348
  * @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
349
  */
312
- export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, hasCheck = true, limits = builderLimits(), now = Date.now, pickCheck }) {
350
+ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, hasCheck = true, limits = builderLimits(), now = Date.now, pickCheck, cartridge: cartridgeFor, orchestra, slices: slicesFor, polish, explore }) {
313
351
  const plan = readPlan(cwd, sessionId)
314
352
  if (!plan) throw new VerifyError("There's no plan yet: call kriya_plan first.")
315
353
  if (!Number.isInteger(n) || n < 1 || n > plan.steps.length) throw new VerifyError(`The plan has steps 1 to ${plan.steps.length}.`)
@@ -337,7 +375,15 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
337
375
  let start = guard ? await save?.(`before step ${n}`) : undefined
338
376
  const base = start
339
377
  const briefing = (await guard?.briefing?.(plan.steps[n - 1])) ?? []
378
+ // Harness 2.0: one cartridge for every attempt of this step (undefined: the prompt as before)
379
+ const cartridge = cartridgeFor ? await cartridgeFor(plan.steps[n - 1]).catch(() => undefined) : undefined
380
+ const slices = slicesFor && plan.steps[n - 1].contracts?.length ? slicesFor(plan.steps[n - 1]) : ""
340
381
  let broken = 0
382
+ // Harness 2.0 orchestra: the failure before `previous`, whether a head-level builder already
383
+ // ran on this step, and a one-time "use the head" instead of a stall (ARCHITECTURE §5)
384
+ let earlierRun
385
+ let headTried = false
386
+ let forceHead = false
341
387
  const rollBack = async (why) => {
342
388
  if (!guard?.restore || !base) return false
343
389
  await guard.restore(base, why)
@@ -345,19 +391,36 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
345
391
  writeProgress(root, sessionId, { ...progress, rollbacks: (progress.rollbacks ?? 0) + 1 })
346
392
  return true
347
393
  }
394
+ // Harness 2.0 W14 (WD-18): a step marked explore builds its takes first (only with explore given)
395
+ const takes = explore && status[n - 1].status !== "pass" && status[n - 1].attempts === 0 ? plan.steps[n - 1].explore : undefined
396
+ if (takes) {
397
+ if (explore.readOnly) throw new VerifyError("Read only mode can't explore: each take changes files.")
398
+ const done = await exploreTakes({ plan, n, label, takes, root, cwd, sessionId, spawn, verify, explore, cartridge, slices, briefing, limits, hasCheck, v2, orchestra, builders, now })
399
+ if (done.result) return done.result
400
+ // No take passed: the normal retry rules go on from the best-ranked failure
401
+ previous = done.previous
402
+ start = done.tree
403
+ status[n - 1] = { ...status[n - 1], status: "fail", attempts: done.attempts }
404
+ }
348
405
  for (;;) {
349
406
  const before = status[n - 1]
350
407
  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
408
  const live = { n, attempt: builders.length + 1, startedAt: now(), steps: 0 }
409
+ const tier = orchestra?.tier({ attempt: (before.attempts ?? 0) + 1, previous, earlier: earlierRun, force: forceHead, step: plan.steps[n - 1] })
410
+ if (tier) {
411
+ live.tier = tier
412
+ if (tier === orchestra.head) headTried = true
413
+ }
414
+ forceHead = false
352
415
  building.set(sessionId, live)
353
416
  let built
354
417
  try {
355
- built = await spawn(builderPrompt(plan, n, previous, v2?.rules, { limits, checked: hasCheck, briefing }), `Step ${n}: ${plan.steps[n - 1].title}`, live)
418
+ built = await spawn(builderPrompt(plan, n, previous, v2?.rules, { limits, checked: hasCheck, briefing, ...(cartridge && { cartridge }), ...(slices && { slices }) }), `Step ${n}: ${plan.steps[n - 1].title}`, live)
356
419
  } finally {
357
420
  if (building.get(sessionId) === live) building.delete(sessionId)
358
421
  }
359
422
  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 }) })
423
+ 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 }), ...(cartridge && { cartridge: `${cartridge.id}@${cartridge.version}` }), ...(live.tier && { tier: live.tier }), ...(live.advice && { advice: live.advice }) })
361
424
  const tree = await save?.(`attempt ${builders.length} of step ${n}`)
362
425
  const untouched = tree !== undefined && tree === start
363
426
  if (guard && built.stopReason === "error" && untouched && noteInterruption(root, sessionId, label))
@@ -387,15 +450,45 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
387
450
  const judged = verdict(readProgress(root, sessionId)).steps
388
451
  for (const b of built.filter((b) => !judged.some((s) => s.step === b.step))) checked.verdict = (await verify(b.step)).verdict
389
452
  }
453
+ // Harness 2.0 W6 (WD-13): after a pass, the critic may earn one polish attempt; kept only if
454
+ // every check and gate still passes, otherwise the passing files go back and are checked again
455
+ if (checked.status === "pass" && polish) {
456
+ const failures = verdict(readProgress(root, sessionId)).steps.find((s) => s.step === label)?.failures ?? 0
457
+ const defects = failures + 1 < MAX_ATTEMPTS ? ((await polish.critique(plan.steps[n - 1], n).catch(() => [])) ?? []).filter((d) => d.severity === "major") : []
458
+ const passing = defects.length ? await polish.snapshot(`step ${n} passed, before polish`).catch(() => undefined) : undefined
459
+ if (passing) {
460
+ const live = { n, attempt: builders.length + 1, startedAt: now(), steps: 0, polish: true }
461
+ const tier = orchestra?.tier({ attempt: MAX_ATTEMPTS, step: plan.steps[n - 1] })
462
+ if (tier) live.tier = tier
463
+ building.set(sessionId, live)
464
+ let built
465
+ try {
466
+ built = await spawn(builderPrompt(plan, n, undefined, v2?.rules, { limits, checked: hasCheck, briefing, ...(cartridge && { cartridge }), ...(slices && { slices }), polish: defects }), `Step ${n}: ${plan.steps[n - 1].title} (polish)`, live)
467
+ } finally {
468
+ if (building.get(sessionId) === live) building.delete(sessionId)
469
+ }
470
+ builders.push({ stopReason: built.stopReason ?? "completed", summary: textOf(built.output).slice(-600), steps: live.steps, polish: true })
471
+ noteBuilder(root, sessionId, { step: label, stopReason: builders.at(-1).stopReason, steps: live.steps, ms: now() - live.startedAt, polish: defects.length, ...(live.tier && { tier: live.tier }), ...(cartridge && { cartridge: `${cartridge.id}@${cartridge.version}` }) })
472
+ const after = await verify(label)
473
+ if (after.status === "pass") return { status: "pass", step: n, title: plan.steps[n - 1].title, attempts: after.attempts, builders, command: after.command, output: "", verdict: after.verdict, polished: defects.length }
474
+ await polish.restore(passing, `polish of step ${n} broke a check`)
475
+ const again = await verify(label)
476
+ return { status: again.status, step: n, title: plan.steps[n - 1].title, attempts: again.attempts, builders, command: again.command, output: again.output ?? "", verdict: again.verdict, polishReverted: true }
477
+ }
478
+ }
390
479
  if (checked.status === "pass" || checked.status === "blocked")
391
480
  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
481
  const earlier = previous
482
+ earlierRun = earlier
393
483
  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
484
  const repeated = guard && checked.signature && earlier?.sig === checked.signature
395
485
  // A builder that died on an error says nothing about the code; its attempts just run out
396
486
  // Only exit 126/127 proves the command can't run; ENOENT or a missing module can be the code's own bug
397
487
  const cantRun = checked.exitCode === 126 || checked.exitCode === 127
398
- if (repeated && built.stopReason !== "error" && (untouched || cantRun)) {
488
+ // Orchestra: a worker that repeats itself without changing a file gets one head-level attempt
489
+ // first; the head repeating itself, or a check that can't run, stalls exactly as before
490
+ if (repeated && built.stopReason !== "error" && untouched && !cantRun && orchestra && !headTried) forceHead = true
491
+ else if (repeated && built.stopReason !== "error" && (untouched || cantRun)) {
399
492
  const reason = untouched ? "the same failure again with no file changed" : "the check can't run on this machine"
400
493
  const after = markStalled(root, sessionId, reason)
401
494
  const undone = await rollBack(`step ${n} blocked`)
@@ -426,3 +519,102 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
426
519
  status[n - 1] = { ...before, status: "fail", attempts: checked.attempts }
427
520
  }
428
521
  }
522
+
523
+ /**
524
+ * Harness 2.0 W14 (WD-18): Explore. `takes` (2–3) builders one after another
525
+ * in the same folder, each from the step's starting files with its own
526
+ * direction hint (src/explore.js), each snapshotted and checked (a failed take
527
+ * counts as an attempt). Passing takes are offered to the person (`pick`);
528
+ * with no answer, the critic's ranking (`rank`), else take order, decides. The
529
+ * kept take's files are restored and checked again, so the step's last run is
530
+ * the kept take's; every take stays in `kriya undo --list`. No polish here,
531
+ * so takes + one retry stays inside MAX_ATTEMPTS.
532
+ * @returns {Promise<{ result?: object, previous?: object, tree?: string, attempts?: number }>}
533
+ */
534
+ async function exploreTakes({ plan, n, label, takes, root, cwd, sessionId, spawn, verify, explore, cartridge, slices, briefing, limits, hasCheck, v2, orchestra, builders, now }) {
535
+ const step = plan.steps[n - 1]
536
+ const hints = directionHints(step.role, takes, root)
537
+ const base = await explore.snapshot(`before explore of step ${n}`)
538
+ const done = []
539
+ for (let v = 1; v <= takes; v++) {
540
+ if (v > 1) await explore.restore(base, `explore: back to the start of step ${n} for take ${v}`)
541
+ const hint = hints[v - 1]
542
+ const served = await explore.served?.()
543
+ const live = { n, attempt: builders.length + 1, startedAt: now(), steps: 0, take: v }
544
+ // Takes are built on the worker level (the first attempt's level)
545
+ const tier = orchestra?.tier({ attempt: 1, step })
546
+ if (tier) live.tier = tier
547
+ building.set(sessionId, live)
548
+ let built
549
+ try {
550
+ const prompt = `${builderPrompt(plan, n, undefined, v2?.rules, { limits, checked: hasCheck, briefing, ...(cartridge && { cartridge }), ...(slices && { slices }) })}\n\n${takeSection(v, takes, hint)}`
551
+ built = await spawn(prompt, `Step ${n}: ${step.title} (take ${v} of ${takes})`, live)
552
+ } finally {
553
+ if (building.get(sessionId) === live) building.delete(sessionId)
554
+ }
555
+ builders.push({ stopReason: built.stopReason ?? "completed", summary: textOf(built.output).slice(-600), steps: live.steps, take: v })
556
+ noteBuilder(root, sessionId, { step: label, stopReason: builders.at(-1).stopReason, steps: live.steps, ms: now() - live.startedAt, take: v, direction: hint.id, ...(live.tier && { tier: live.tier }), ...(cartridge && { cartridge: `${cartridge.id}@${cartridge.version}` }) })
557
+ const tree = await explore.snapshot(`explore take ${v} of step ${n}: ${hint.id}`)
558
+ // The dev server must serve this take before any gate looks at it
559
+ const reload = served !== undefined && explore.reloaded ? await explore.reloaded(served) : { ok: true }
560
+ if (!reload.ok) {
561
+ done.push({ v, hint, tree, status: "not checked", reason: reload.reason })
562
+ continue
563
+ }
564
+ const checked = await verify(label)
565
+ done.push({ v, hint, tree, status: checked.status, checked })
566
+ if (checked.status === "blocked") break
567
+ }
568
+ const survivors = done.filter((t) => t.status === "pass")
569
+ const record = (kept, by) => {
570
+ const progress = readProgress(root, sessionId)
571
+ writeProgress(root, sessionId, { ...progress, explore: [...(progress.explore ?? []), { step: label, takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status, tree: t.tree, ...(t.reason && { reason: t.reason }) })), ...(kept && { kept, by }) }] })
572
+ }
573
+ if (!survivors.length) {
574
+ record(undefined)
575
+ // A take the dev server never served wasn't checked, so it isn't an attempt: stop rather than spend builders past the bound
576
+ const unserved = done.find((t) => t.status === "not checked")
577
+ if (unserved) return { result: { status: "not checked", step: n, title: step.title, builders, note: `Take ${unserved.v} wasn't checked: ${unserved.reason}. Make sure the dev server reloads on file changes, then run the step again.`, explore: { takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status })) } } }
578
+ const failed = done.filter((t) => t.checked && t.status !== "pass")
579
+ const ranked = [...failed].sort((a, b) => (RANK[a.checked.failure] ?? RANK.unknown) - (RANK[b.checked.failure] ?? RANK.unknown) || b.v - a.v)
580
+ const best = ranked.at(-1)
581
+ const attempts = done.reduce((most, t) => Math.max(most, t.checked?.attempts ?? 0), 0)
582
+ if (!best) return { tree: base, attempts }
583
+ if (done.some((t) => t.status === "blocked")) return { result: { status: "blocked", step: n, title: step.title, attempts, builders, command: best.checked.command, output: best.checked.output ?? "", verdict: best.checked.verdict, explore: { takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status })) } } }
584
+ await explore.restore(best.tree, `explore: no take of step ${n} passed; going on from take ${best.v}`)
585
+ const c = best.checked
586
+ return {
587
+ tree: best.tree,
588
+ attempts,
589
+ previous: { attempt: c.attempts, command: c.command, exitCode: c.exitCode, timedOut: c.timedOut, output: c.output, ...(c.failure && { kind: c.failure }), ...(c.signature && { sig: c.signature }), note: `None of the ${takes} takes passed. The files are as take ${best.v} (${best.hint.id}) left them, the closest to passing; fix that take.` },
590
+ }
591
+ }
592
+ let winner
593
+ let by = "only"
594
+ if (survivors.length > 1) {
595
+ const picked = await explore.pick?.(survivors, step, n)
596
+ winner = survivors.find((t) => t.v === picked)
597
+ by = "person"
598
+ if (!winner) {
599
+ const ranked = (await explore.rank?.(survivors, step, n).catch(() => undefined)) ?? []
600
+ winner = survivors.find((t) => t.v === ranked[0]) ?? survivors[0]
601
+ by = ranked.length ? "critic" : "order"
602
+ }
603
+ } else winner = survivors[0]
604
+ await explore.restore(winner.tree, `explore: keep take ${winner.v} of step ${n}`)
605
+ record(winner.v, by)
606
+ const final = await verify(label)
607
+ return {
608
+ result: {
609
+ status: final.status,
610
+ step: n,
611
+ title: step.title,
612
+ attempts: final.attempts,
613
+ builders,
614
+ command: final.command,
615
+ output: final.output ?? "",
616
+ verdict: final.verdict,
617
+ explore: { kept: winner.v, by, direction: winner.hint.id, takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status })) },
618
+ },
619
+ }
620
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,126 @@
1
+ import { createHash } from "node:crypto"
2
+
3
+ import { CLIENT_VERSION } from "./paths.js"
4
+
5
+ // Harness 2.0 W16, MCP P3a (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
6
+ // GROUNDING_AND_CONNECTORS.md §4): servers from the owner's registry that need
7
+ // no sign-in, each tool used only if its full definition still hashes to what
8
+ // the owner pinned. The hash is Kriya's own (lib/mcp/tools.ts definitionHash
9
+ // over lib/agent/episodes.ts canonical), so a device and Kriya agree on drift.
10
+ // A minimal Streamable HTTP client: https only (http only to this machine),
11
+ // no redirects followed, and no credential of any kind sent: no
12
+ // Authorization, no cookie, never the device's Kriya token.
13
+
14
+ const PINNED = ["name", "title", "description", "inputSchema", "outputSchema", "annotations"]
15
+
16
+ /** Kriya's canonical JSON: keys sorted, undefined dropped (lib/agent/episodes.ts). */
17
+ export const canonical = (value) => {
18
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`
19
+ if (value && typeof value === "object") {
20
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined)
21
+ return `{${entries
22
+ .sort(([a], [b]) => (a < b ? -1 : 1))
23
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
24
+ .join(",")}}`
25
+ }
26
+ return JSON.stringify(value)
27
+ }
28
+
29
+ /** The pinned parts of a tool definition, hashed as Kriya hashes them. */
30
+ export function definitionHash(definition) {
31
+ const pinned = Object.fromEntries(PINNED.filter((k) => definition?.[k] !== undefined).map((k) => [k, definition[k]]))
32
+ return createHash("sha256").update(canonical(pinned)).digest("hex")
33
+ }
34
+
35
+ /**
36
+ * The tools a server lists that the owner pinned, unchanged: `{ tool, pin }`.
37
+ * A listed tool with no pin, or whose definition drifted, is left out.
38
+ */
39
+ export function pinnedTools(listed, pins) {
40
+ const out = []
41
+ const dropped = []
42
+ for (const tool of listed ?? []) {
43
+ const pin = (pins ?? []).find((p) => p.name === tool?.name)
44
+ if (!pin) continue
45
+ if (definitionHash(tool) !== pin.definitionHash) dropped.push(tool.name)
46
+ else out.push({ tool, pin })
47
+ }
48
+ return { tools: out, drifted: dropped }
49
+ }
50
+
51
+ export class McpError extends Error {}
52
+
53
+ /** https, or http only to this machine; no credentials in the address. */
54
+ export function serverUrl(text) {
55
+ let url
56
+ try {
57
+ url = new URL(text)
58
+ } catch {
59
+ throw new McpError("That isn't a server address.")
60
+ }
61
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
62
+ if (url.username || url.password) throw new McpError("A server address carries no credentials.")
63
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new McpError("Registry servers are https.")
64
+ return url
65
+ }
66
+
67
+ const PROTOCOL = "2025-06-18"
68
+
69
+ /** One server's session: initialize, list, call. `fetchImpl` for tests. */
70
+ export function mcpSession(address, { fetchImpl = fetch, timeoutMs = 30_000 } = {}) {
71
+ const url = serverUrl(address)
72
+ let session
73
+ let id = 0
74
+ const post = async (body, signal) => {
75
+ const headers = { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": PROTOCOL }
76
+ if (session) headers["mcp-session-id"] = session
77
+ const response = await fetchImpl(url, { method: "POST", headers, body: JSON.stringify(body), redirect: "error", signal: signal ?? AbortSignal.timeout(timeoutMs) })
78
+ const next = response.headers.get("mcp-session-id")
79
+ if (next) session = next
80
+ return response
81
+ }
82
+ async function request(method, params, signal) {
83
+ const want = ++id
84
+ const response = await post({ jsonrpc: "2.0", id: want, method, params }, signal)
85
+ if (!response.ok) throw new McpError(`The server answered ${response.status}.`)
86
+ const type = response.headers.get("content-type") ?? ""
87
+ let message
88
+ if (type.includes("text/event-stream")) {
89
+ const text = await response.text()
90
+ for (const line of text.split("\n")) {
91
+ if (!line.startsWith("data:")) continue
92
+ try {
93
+ const m = JSON.parse(line.slice(5))
94
+ if (m?.id === want) message = m
95
+ } catch {
96
+ // Not a message
97
+ }
98
+ }
99
+ } else message = await response.json()
100
+ if (!message) throw new McpError("The server sent no answer.")
101
+ if (message.error) throw new McpError(`The server refused: ${String(message.error.message ?? "error").slice(0, 300)}`)
102
+ return message.result
103
+ }
104
+ return {
105
+ async open() {
106
+ await request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "kriya-harness", version: CLIENT_VERSION } })
107
+ await post({ jsonrpc: "2.0", method: "notifications/initialized" })
108
+ },
109
+ async tools() {
110
+ const all = []
111
+ let cursor
112
+ for (let page = 0; page < 10; page++) {
113
+ const result = await request("tools/list", cursor ? { cursor } : {})
114
+ all.push(...(result?.tools ?? []))
115
+ cursor = result?.nextCursor
116
+ if (!cursor) break
117
+ }
118
+ return all
119
+ },
120
+ call: (name, args, signal) => request("tools/call", { name, arguments: args ?? {} }, signal),
121
+ }
122
+ }
123
+
124
+ /** A model-facing name: mcp__<server>__<tool>, within DeepSeek's function-name rules. */
125
+ export const toolName = (serverId, name) =>
126
+ `mcp__${serverId}__${name}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64)