@kriya-ai/harness 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,12 +29,17 @@
29
29
  # cap; the others keep DSH's defaults (262,144 and 32,768). A tier
30
30
  # Kriya says takes images (KRIYA_MODEL_IMAGES) declares it, else
31
31
  # DSH refuses every image for it
32
+ # Harness 2.0: with the owner's orchestra and the local relay, an
33
+ # "Orchestration" choice first (KRIYA_ORCHESTRA_PICK, from the launcher):
34
+ # the head's limits and images; the relay sends it to Kriya as the head tier
32
35
  models: !!js >-
33
- ((names, limits) => [['balanced', 'Kriya balanced'], ['budget', 'Kriya budget'], ['escalation', 'Kriya escalation']]
36
+ ((names, limits) => [...(process.env.KRIYA_ORCHESTRA_PICK && process.env.KRIYA_ORCHESTRA_HEAD ? [[process.env.KRIYA_ORCHESTRA_PICK, process.env.KRIYA_ORCHESTRA_NAME || 'Orchestration', process.env.KRIYA_ORCHESTRA_HEAD]] : []),
37
+ ...[['balanced', 'Kriya balanced'], ['budget', 'Kriya budget'], ['escalation', 'Kriya escalation']]
34
38
  .filter(([id]) => (process.env.KRIYA_ALLOWED_TIERS || 'balanced,budget,escalation').split(',').includes(id))
35
- .map(([id, name]) => ({ id, name: typeof names[id] === 'string' && names[id] ? names[id] : name,
36
- ...((process.env.KRIYA_MODEL_IMAGES || '').split(',').includes(id) ? { input: ['text', 'image'] } : {}),
37
- ...(limits[id] ? { contextWindow: limits[id].contextWindow, maxTokens: limits[id].maxTokens } : {}) })))
39
+ .map(([id, name]) => [id, typeof names[id] === 'string' && names[id] ? names[id] : name, id])]
40
+ .map(([id, name, tier]) => ({ id, name,
41
+ ...((process.env.KRIYA_MODEL_IMAGES || '').split(',').includes(tier) ? { input: ['text', 'image'] } : {}),
42
+ ...(limits[tier] ? { contextWindow: limits[tier].contextWindow, maxTokens: limits[tier].maxTokens } : {}) })))
38
43
  ((() => { try { return JSON.parse(process.env.KRIYA_MODEL_NAMES || '{}') } catch { return {} } })(),
39
44
  (() => { try { return JSON.parse(process.env.KRIYA_MODEL_LIMITS || '{}') } catch { return {} } })())
40
45
 
@@ -45,7 +50,8 @@
45
50
  config:
46
51
  modelPolicies: !!js >-
47
52
  Object.entries((() => { try { return JSON.parse(process.env.KRIYA_MODEL_LIMITS || '{}') } catch { return {} } })())
48
- .map(([model, l]) => ({ provider: 'kriya', model, headroomTokens: l.headroomTokens }))
53
+ .flatMap(([model, l]) => [model, ...(process.env.KRIYA_ORCHESTRA_PICK && process.env.KRIYA_ORCHESTRA_HEAD === model ? [process.env.KRIYA_ORCHESTRA_PICK] : [])]
54
+ .map((id) => ({ provider: 'kriya', model: id, headroomTokens: l.headroomTokens })))
49
55
 
50
56
  # The starting tier: balanced, or the best tier the plan allows, chosen by
51
57
  # the launcher from GET /models (src/launch.js startTier)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kriya-ai/harness",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Kriya Harness (beta): a Kriya agent on your machine, built on DeepSeek Harness",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -7,7 +7,7 @@ import { extname, join, resolve } from "node:path"
7
7
 
8
8
  import { cartridgeSource, ROLES, selectCartridge } from "../../src/cartridges.js"
9
9
  import { checkpoint, restoreTree } from "../../src/checkpoints.js"
10
- import { escalateAfterFromEnv, orchestraFromEnv, tierFor } from "../../src/orchestra.js"
10
+ import { escalateAfterFromEnv, orchestraFromEnv, sessionOrchestrated, tierFor } from "../../src/orchestra.js"
11
11
  import { contractSlices, CONTRACT_NAMES } from "../../src/contracts.js"
12
12
  import { recordOutcome } from "../../src/outcomes.js"
13
13
  import { bindPlan, checkPlanAllowed, MAX_MILESTONES, milestonesText, saveMilestones, syncMilestones } from "../../src/milestones.js"
@@ -397,7 +397,7 @@ export function stepTool(host) {
397
397
  ...(host.guardSteps && { guard: host.guardSteps(exec, cwd) }),
398
398
  ...(host.questions && { pickCheck: (found) => askCheck(host.questions(), exec, found) }),
399
399
  ...(host.cartridge && { cartridge: host.cartridge }),
400
- ...(host.orchestra && { orchestra: host.orchestra }),
400
+ ...(host.orchestra && (host.orchestrated?.(exec) ?? true) && { orchestra: host.orchestra }),
401
401
  ...(host.contracts && { slices: (step) => contractSlices(projectRoot(cwd), step.contracts) }),
402
402
  ...(host.polish && { polish: host.polish(exec, cwd) }),
403
403
  ...(host.explore && { explore: host.explore(exec, cwd) }),
@@ -828,6 +828,10 @@ export function apply(ctx) {
828
828
  }
829
829
  // Harness 2.0 orchestra (--orchestra, Kriya's offer): builders on the worker level, the head after
830
830
  const levels = orchestraFromEnv()
831
+ // With the picker's Orchestration choice (KRIYA_ORCHESTRA_PICK), the split is for the sessions that chose it;
832
+ // a session on a single model runs its steps on that model. Without the choice, every session, as before
833
+ const pick = process.env.KRIYA_ORCHESTRA_PICK
834
+ const orchestrated = (exec) => sessionOrchestrated(levels, pick, exec.agent?.session?.requestHeader?.()?.config?.model ?? exec.agent?.options?.model)
831
835
  // KRHE's escalateAfter (W10): a profile pins it through the environment; else the default
832
836
  const escalateAfter = escalateAfterFromEnv()
833
837
  // Harness 2.0 milestones (--milestones, WD-12)
@@ -851,7 +855,7 @@ export function apply(ctx) {
851
855
  activation = await subagents.startActivation({
852
856
  provider: "spawn",
853
857
  label: `Review step ${n}`,
854
- request: { prompt: [{ type: "text", text: critiquePrompt({ role: chosen?.cartridge.role, judgement: chosen?.cartridge.judgement, plan, n, changed, notes }) }], parent: exec.agent, signal: exec.signal, maxDepth: 1, ...(levels && { agentOptions: { model: levels.head } }) },
858
+ request: { prompt: [{ type: "text", text: critiquePrompt({ role: chosen?.cartridge.role, judgement: chosen?.cartridge.judgement, plan, n, changed, notes }) }], parent: exec.agent, signal: exec.signal, maxDepth: 1, ...(orchestrated(exec) && { agentOptions: { model: levels.head } }) },
855
859
  signal: exec.signal,
856
860
  delivery: "caller",
857
861
  })
@@ -884,6 +888,7 @@ export function apply(ctx) {
884
888
  },
885
889
  }),
886
890
  ...(gatesOn && { contracts: CONTRACT_NAMES }),
891
+ ...(levels && { orchestrated }),
887
892
  ...(levels && { orchestra: { head: levels.head, tier: (input) => tierFor({ orchestra: levels, ...input, role: input.step?.role, ...(escalateAfter !== undefined && { escalateAfter }) }) } }),
888
893
  ...(milestonesOn && { milestones: true }),
889
894
  // Harness 2.0 W14 (WD-18): Explore takes; never in Read only (runStep refuses), needs roles
@@ -981,7 +986,7 @@ export function apply(ctx) {
981
986
  })
982
987
  const id = String(activation.childId)
983
988
  builders.add(id)
984
- if (levels && live) advising.set(id, { head: exec.agent, live, cwd: await host.cwd(exec), n: live.n })
989
+ if (levels && live?.tier) advising.set(id, { head: exec.agent, live, cwd: await host.cwd(exec), n: live.n })
985
990
  if (live) guard.start(id, live)
986
991
  masks.delete(exec.agent)
987
992
  const stop = () => activation.dispose().catch(() => {})
@@ -327,6 +327,16 @@ window.__ModuleLoader__.load({
327
327
  React.Fragment,
328
328
  null,
329
329
  Section("Repository", h(React.Fragment, null, h("div", { className: "kh-tx-row" }, h("b", null, d.repo.state)), h("div", { className: "kh-tx-note", style: { whiteSpace: "pre-line" } }, d.repo.text)), refresh),
330
+ d.workforce &&
331
+ Section(
332
+ "Harness 2.0",
333
+ h(
334
+ React.Fragment,
335
+ null,
336
+ h("div", { className: "kh-tx-row" }, d.workforce.orchestra ? `Orchestra: head ${d.workforce.orchestra.headName ?? d.workforce.orchestra.head}, worker ${d.workforce.orchestra.workerName ?? d.workforce.orchestra.worker}` : "Orchestra: off (one level for everything)"),
337
+ h("div", { className: "kh-tx-grid" }, d.workforce.switches.flatMap((x) => [h("span", { key: `${x.flag}a`, className: "kh-tx-mono" }, x.flag), h("span", { key: `${x.flag}b`, className: x.on ? "" : "kh-tx-note" }, x.on ? "on" : "off")]))
338
+ )
339
+ ),
330
340
  Section("MCP servers", d.mcp.length ? d.mcp.map((m) => h("div", { key: m.id, className: "kh-tx-row" }, m.name)) : h("div", { className: "kh-tx-note" }, "None offered (kriya --mcp, and the owner's registry).")),
331
341
  Section(
332
342
  "What can be checked here",
@@ -8,6 +8,7 @@ import { listCheckpoints, restoreTree, trackedRoot } from "../../src/checkpoints
8
8
  import { gateMatrix } from "../../src/doctor.js"
9
9
  import { liveBuild } from "../../src/loop.js"
10
10
  import { readMilestones } from "../../src/milestones.js"
11
+ import { SWITCHES } from "../../src/modes.js"
11
12
  import { orchestraFromEnv } from "../../src/orchestra.js"
12
13
  import { kriyaHome } from "../../src/paths.js"
13
14
  import { readState } from "../../src/release.js"
@@ -84,6 +85,16 @@ export function spendTracker({ account }) {
84
85
  }
85
86
  }
86
87
 
88
+ /** What this harness was launched with: the head and worker levels (with their models' names) and each switch. */
89
+ export function workforceOf(env = process.env) {
90
+ const o = orchestraFromEnv(env)
91
+ const named = names(env)
92
+ return {
93
+ orchestra: o ? { head: o.head, worker: o.worker, headName: named[o.head] ?? null, workerName: named[o.worker] ?? null } : null,
94
+ switches: SWITCHES.map(([flag, name]) => ({ flag, on: env[name] === "on" })),
95
+ }
96
+ }
97
+
87
98
  /** Ledgers on this computer: ~/.kriya/progress/<project>/milestones.json, each with its project's folder from a session record beside it. */
88
99
  export function ledgers(home = kriyaHome()) {
89
100
  const dir = join(home, "progress")
@@ -215,7 +226,7 @@ export function handlers(host) {
215
226
  (host.matrix ?? gateMatrix)(),
216
227
  (host.mcp ?? (async () => []))().catch(() => []),
217
228
  ])
218
- return { repo, matrix, mcp }
229
+ return { repo, matrix, mcp, workforce: workforceOf(env) }
219
230
  }
220
231
  throw new ChangesError("Which part?")
221
232
  }
@@ -77,7 +77,11 @@ export async function ensureHost({ env = process.env, home = kriyaHome(), stamp
77
77
 
78
78
  /** Stops the Host and waits until it's gone. */
79
79
  export async function stopHost(home = kriyaHome()) {
80
+ const live = await contact(home)
80
81
  await hostCall(home, "POST", "/internal/stop").catch(() => null)
81
82
  const started = Date.now()
82
83
  while ((await contact(home)) && Date.now() - started < START_MS) await new Promise((done) => setTimeout(done, 25))
84
+ // The Host closes its channel first, then removes its token, socket and lock and exits: until the
85
+ // process is gone a caller could still read the old token (found on CI, edit-tp11)
86
+ if (live?.pid) await gone(live.pid)
83
87
  }
@@ -32,7 +32,8 @@ const unavailable = (message) => {
32
32
  /**
33
33
  * @param {{ db: ReturnType<import("./db.js").openIndexDb>, cache: string, binDir: string, language?: string, run?: typeof runTool, runtime?: () => object | null, acquire?: (resources: string[], signal?: AbortSignal) => Promise<() => void> }} options
34
34
  */
35
- export function createIndexer({ db, cache, binDir, language = "en", run = runTool, runtime = () => activeRuntime(), acquire = async () => () => {} }) {
35
+ // platform: which face helper this system has (faces.js); a parameter so tests that fake every tool can say which system they fake
36
+ export function createIndexer({ db, cache, binDir, language = "en", run = runTool, runtime = () => activeRuntime(), acquire = async () => () => {}, platform = process.platform }) {
36
37
  const layers = {
37
38
  L0: {
38
39
  version: PROBE_VERSION,
@@ -138,7 +139,7 @@ export function createIndexer({ db, cache, binDir, language = "en", run = runToo
138
139
  needs: ["L6"],
139
140
  async run({ path, facts, signal, fingerprint }) {
140
141
  if (!facts.width) unavailable("This file has no picture.")
141
- const helper = await faceHelper(binDir, run)
142
+ const helper = await faceHelper(binDir, run, platform)
142
143
  if (helper.missing) unavailable(helper.missing)
143
144
  const folder = join(cache, "faces", fingerprint)
144
145
  rmSync(folder, { recursive: true, force: true })
@@ -26,11 +26,17 @@ export const CEILINGS = Object.freeze({
26
26
  /** Each viewport, its device pixel ratio (above every cap, so an uncapped ratio shows) and the tier it is judged against. */
27
27
  export const VIEWPORTS_3D = Object.freeze([
28
28
  Object.freeze({ name: "390", width: 390, height: 844, dpr: 3, tiers: ["low", "mid", "high"] }),
29
- Object.freeze({ name: "1440", width: 1440, height: 900, dpr: 3, tiers: ["high", "mid", "low"] }),
29
+ // DPR 2, not 3: a 4,320 px software-rendered buffer (CI has no GPU) costs minutes and shows nothing DPR 2 doesn't
30
+ Object.freeze({ name: "1440", width: 1440, height: 900, dpr: 2, tiers: ["high", "mid", "low"] }),
30
31
  ])
31
32
  export const FRAMES = 120
32
33
  export const LEAK_SLACK = 0.05
33
- const FRAME_WAIT_MS = 8_000
34
+ // Each wait for frames is bounded by wall time: on a software renderer (no GPU, as on CI) a heavy scene
35
+ // draws a few frames a second, so the gate measures the frames that came instead of waiting for 120
36
+ const FRAME_WAIT_MS = 3_000
37
+ const SHOT_MS = 10_000
38
+ /** The whole gate's time budget: what isn't checked by then is reported not checked, never passed */
39
+ export const GATE_MS = 60_000
34
40
  const NAV_MS = 30_000
35
41
  const RESTORE_WAIT_MS = 2_000
36
42
  const DIRECTION = "scene_direction.json"
@@ -165,6 +171,7 @@ export const WRAP = `(() => {
165
171
  raf(tick)
166
172
  let lost = null
167
173
  const read = (action) => {
174
+ if (action === "frames") return frames.length
168
175
  const live = contexts.filter((c) => !c.gl.isContextLost())
169
176
  if (action === "lose") {
170
177
  const c = live.filter((x) => x.canvas.isConnected).sort((a, b) => b.canvas.clientWidth * b.canvas.clientHeight - a.canvas.clientWidth * a.canvas.clientHeight)[0]
@@ -260,13 +267,13 @@ const evidenceDir = (root, label) =>
260
267
  * given (tests); otherwise the stack's app and the project's scene_direction.json.
261
268
  * @returns {Promise<{ id: "G-3D", status: "pass" | "fail" | "not_checked", reason?: string, kind?: string, excerpt?: string, note?: string, optional?: true, report?: any }>}
262
269
  */
263
- export async function threeGate({ root, label, launch, app: givenApp, direction: givenDirection }) {
270
+ export async function threeGate({ root, label, launch, app: givenApp, direction: givenDirection, budgetMs }) {
264
271
  const app = givenApp ?? readStack(root).app
265
272
  if (!app) return { id: "G-3D", status: "not_checked", reason: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)", optional: true }
266
273
  const direction = givenDirection ?? readDirection(root)
267
274
  if (!direction) return { id: "G-3D", status: "not_checked", reason: `no ${DIRECTION} with routes in .kriya/contracts (the designer step writes it)`, optional: true }
268
275
  const dir = evidenceDir(root, label)
269
- const run = await withGateBrowser((_open, browser) => checkScenes(browser, app, direction, dir), { launch })
276
+ const run = await withGateBrowser((_open, browser) => checkScenes(browser, app, direction, dir, budgetMs ? { budgetMs } : {}), { launch })
270
277
  if (run.unavailable) return { id: "G-3D", status: "not_checked", reason: run.unavailable }
271
278
  return run.value
272
279
  }
@@ -296,19 +303,23 @@ async function openPage(browser, url, { viewport, reducedMotion = "no-preference
296
303
  }
297
304
  const read = (action) => page.evaluate(({ name, action }) => window[name]?.(action), { name: READ, action })
298
305
  const framesFrom = async (from, n = FRAMES) => {
299
- await page.waitForFunction(({ name, want }) => (window[name]?.().frames ?? 0) >= want, { name: READ, want: from + n }, { timeout: FRAME_WAIT_MS, polling: 50 }).catch(() => {})
306
+ await page.waitForFunction(({ name, want }) => (window[name]?.("frames") ?? 0) >= want, { name: READ, want: from + n }, { timeout: FRAME_WAIT_MS, polling: 50 }).catch(() => {})
300
307
  return read()
301
308
  }
302
309
  const shot = async () => {
303
310
  const canvas = page.locator("canvas").first()
304
311
  if (!(await canvas.count())) return null
305
- return canvas.screenshot({ timeout: 5_000 }).catch(() => null)
312
+ return canvas.screenshot({ timeout: SHOT_MS }).catch(() => null)
306
313
  }
307
314
  return { page, context, read, framesFrom, shot, consoleErrors, bytes: () => bytes, started }
308
315
  }
309
316
 
310
- async function checkScenes(browser, app, direction, dir) {
317
+ async function checkScenes(browser, app, direction, dir, { budgetMs = GATE_MS } = {}) {
318
+ const deadline = Date.now() + budgetMs
319
+ const late = () => Date.now() > deadline
311
320
  const problems = []
321
+ // Checks that couldn't be made here (e.g. a screenshot that timed out): never a pass, never a made-up failure
322
+ const unknown = []
312
323
  const reported = []
313
324
  const motion = direction.motion ?? "none"
314
325
  // Does this browser make WebGL at all? Otherwise not_checked, never pass
@@ -321,6 +332,10 @@ async function checkScenes(browser, app, direction, dir) {
321
332
  for (const route of direction.routes)
322
333
  for (const viewport of VIEWPORTS_3D) {
323
334
  const at = `${route.path} at ${viewport.name}px`
335
+ if (late()) {
336
+ unknown.push(`${at}: not reached within the gate's ${budgetMs / 1000} s budget (the scene draws slowly here)`)
337
+ continue
338
+ }
324
339
  const budget = budgetFor(direction.tiers, viewport.tiers)
325
340
  const v = await openPage(browser, new URL(route.path, app).href, { viewport })
326
341
  if (v.unreachable) return { id: "G-3D", status: "not_checked", reason: `${app}${route.path} doesn't answer (${v.unreachable})` }
@@ -341,7 +356,8 @@ async function checkScenes(browser, app, direction, dir) {
341
356
  keepShot(dir, `${route.path.replace(/\W+/g, "_") || "root"}-${viewport.name}-f90.png`, b)
342
357
  if (v.consoleErrors.length) problems.push(`${at}: console errors (shader compile and link failures are logged here): ${v.consoleErrors.slice(0, 3).join(" | ")}`)
343
358
  if (r.errors) problems.push(`${at}: ${r.errors} WebGL error${r.errors === 1 ? "" : "s"} (gl.getError) while drawing`)
344
- if (blank(lookB)) problems.push(`${at}: the canvas is blank or one colour (${lookB ? `${lookB.colours} colours` : "no screenshot"}); check the shader, the camera and the light`)
359
+ if (!lookA || !lookB) unknown.push(`${at}: the canvas couldn't be captured to check it draws`)
360
+ else if (blank(lookB)) problems.push(`${at}: the canvas is blank or one colour (${lookB.colours} colours); check the shader, the camera and the light`)
345
361
  else if (motion !== "none" && moved(lookA, lookB) === 0) problems.push(`${at}: motion is "${motion}" in the direction, but frame 30 and frame 90 are identical`)
346
362
  const recent = r.recent ?? []
347
363
  const drawCalls = median(recent.map((f) => f.draws))
@@ -354,8 +370,12 @@ async function checkScenes(browser, app, direction, dir) {
354
370
  if (sizing) problems.push(`${at}: ${sizing}`)
355
371
  const deltas = recent.map((f) => f.ms).filter((ms) => ms > 0 && ms < 1000)
356
372
  reported.push(`${at}: ${drawCalls} draws, ${Math.round(tris)} triangles, ${mb(r.textureBytes)} textures, frame ${median(deltas).toFixed(1)} ms median / ${p95(deltas).toFixed(1)} ms p95 (reported, not gated)`)
357
- // The deeper checks once per route, at the phone width
373
+ // The deeper checks once per route, at the phone width, while the budget lasts
358
374
  if (viewport !== VIEWPORTS_3D[0]) continue
375
+ if (late()) {
376
+ unknown.push(`${at}: resize, leak and context-loss checks not reached within the gate's ${budgetMs / 1000} s budget`)
377
+ continue
378
+ }
359
379
  // Resize: the buffer follows the new CSS size
360
380
  await v.page.setViewportSize({ width: viewport.width - 60, height: viewport.height - 100 })
361
381
  const resized = await v.framesFrom((await v.read()).frames, 20)
@@ -379,13 +399,15 @@ async function checkScenes(browser, app, direction, dir) {
379
399
  await v.page.waitForTimeout(RESTORE_WAIT_MS)
380
400
  const after = await v.read()
381
401
  const look = canvasLook(await v.shot())
382
- if (after.canvas?.lost || blank(look)) problems.push(`${at}: after a lost and restored WebGL context the canvas stays ${after.canvas?.lost ? "lost" : "blank"}; prevent default on webglcontextlost and rebuild on webglcontextrestored`)
402
+ if (!after.canvas?.lost && !look) unknown.push(`${at}: the canvas couldn't be captured after a restored context`)
403
+ else if (after.canvas?.lost || blank(look)) problems.push(`${at}: after a lost and restored WebGL context the canvas stays ${after.canvas?.lost ? "lost" : "blank"}; prevent default on webglcontextlost and rebuild on webglcontextrestored`)
383
404
  } else reported.push(`${at}: context loss not checked (no WEBGL_lose_context)`)
384
405
  } finally {
385
406
  await v.context.close().catch(() => {})
386
407
  }
387
408
  // Reduced motion: decorative motion stops
388
- if (motion !== "none" && viewport === VIEWPORTS_3D[0]) {
409
+ if (motion !== "none" && viewport === VIEWPORTS_3D[0] && late()) unknown.push(`${at}: reduced motion not checked within the gate's ${budgetMs / 1000} s budget`)
410
+ else if (motion !== "none" && viewport === VIEWPORTS_3D[0]) {
389
411
  const q = await openPage(browser, new URL(route.path, app).href, { viewport, reducedMotion: "reduce" })
390
412
  if (!q.unreachable)
391
413
  try {
@@ -393,14 +415,16 @@ async function checkScenes(browser, app, direction, dir) {
393
415
  const a = canvasLook(await q.shot())
394
416
  await q.framesFrom((await q.read()).frames, 60)
395
417
  const b = canvasLook(await q.shot())
396
- if (moved(a, b) > 0) problems.push(`${at}: decorative motion still runs under prefers-reduced-motion`)
418
+ if (!a || !b) unknown.push(`${at}: the canvas couldn't be captured under reduced motion`)
419
+ else if (moved(a, b) > 0) problems.push(`${at}: decorative motion still runs under prefers-reduced-motion`)
397
420
  } finally {
398
421
  await q.context.close().catch(() => {})
399
422
  }
400
423
  }
401
424
  }
402
- const note = [`renderer: ${renderer ?? "unknown"}`, ...reported].join("\n")
425
+ const note = [`renderer: ${renderer ?? "unknown"}`, ...reported, ...unknown.map((u) => `not checked: ${u}`)].join("\n")
403
426
  if (problems.length) return { id: "G-3D", status: "fail", kind: "gate", excerpt: `G-3D:\n${problems.slice(0, 12).map((p) => `- ${p}`).join("\n")}${problems.length > 12 ? `\n- … and ${problems.length - 12} more` : ""}\n(${note.split("\n")[0]})`, note }
427
+ if (unknown.length) return { id: "G-3D", status: "not_checked", reason: unknown[0], note }
404
428
  return { id: "G-3D", status: "pass", note }
405
429
  }
406
430
 
@@ -75,6 +75,24 @@ async function readAll(req) {
75
75
  return Buffer.concat(chunks)
76
76
  }
77
77
 
78
+ // Harness 2.0: the picker's local aliases (the "orchestra" choice), turned into the
79
+ // plan tier they stand for before a request leaves this computer, so Kriya only
80
+ // ever sees its own tier names (track H rule 4). Any other body passes untouched.
81
+ export const ORCHESTRA_ALIAS = "orchestra"
82
+ export function aliased(body, path, headers, aliases) {
83
+ if (!body || !Object.keys(aliases).length || !path.endsWith("/chat/completions") || !/^application\/json\b/i.test(headers["content-type"] ?? "")) return body
84
+ const text = body.toString("utf8")
85
+ if (!Object.keys(aliases).some((alias) => text.includes(`"${alias}"`))) return body
86
+ let value
87
+ try {
88
+ value = JSON.parse(text)
89
+ } catch {
90
+ return body
91
+ }
92
+ if (typeof value?.model !== "string" || !Object.hasOwn(aliases, value.model)) return body
93
+ return Buffer.from(JSON.stringify({ ...value, model: aliases[value.model] }))
94
+ }
95
+
78
96
  /**
79
97
  * Starts the relay in front of `target` (the signed-in Kriya's address).
80
98
  * `encode`: whether Kriya decodes encoded bodies, as known at launch.
@@ -87,7 +105,7 @@ async function readAll(req) {
87
105
  * @param {{ target: string, encode: boolean, checkSupport?: () => Promise<boolean>, fetchImpl?: typeof fetch, log?: (text: string) => void, now?: () => number, retryMs?: number }} options
88
106
  * @returns {Promise<{ url: string, close: () => Promise<void>, encoding: () => boolean }>} url stands in for device.url inside DSH
89
107
  */
90
- export async function startGatewayProxy({ target, encode, checkSupport, fetchImpl = fetch, log = () => {}, now = Date.now, retryMs = RETRY_MS, outageMs = OUTAGE_MS, outageWaitMs = OUTAGE_WAIT_MS }) {
108
+ export async function startGatewayProxy({ target, encode, checkSupport, aliases = {}, fetchImpl = fetch, log = () => {}, now = Date.now, retryMs = RETRY_MS, outageMs = OUTAGE_MS, outageWaitMs = OUTAGE_WAIT_MS }) {
91
109
  const origin = new URL(target).origin
92
110
  const support = { on: Boolean(encode), checked: now(), pending: null }
93
111
  // One question at a time; a failed question changes nothing
@@ -121,7 +139,7 @@ export async function startGatewayProxy({ target, encode, checkSupport, fetchImp
121
139
  if (body === null) return error(413, "This request is larger than Kriya Harness sends (64 MB).")
122
140
  const headers = {}
123
141
  for (const [name, value] of Object.entries(req.headers)) if (!DROP_REQUEST.has(name) && value !== undefined) headers[name] = Array.isArray(value) ? value.join(", ") : value
124
- const plain = body?.length ? body : undefined
142
+ const plain = aliased(body?.length ? body : undefined, path, headers, aliases)
125
143
  const encodable = Boolean(plain) && /^application\/json\b/i.test(headers["content-type"] ?? "")
126
144
  if (encodable && !support.on && now() - support.checked >= RECHECK_MS) await recheck()
127
145
  const once = (encoded) => {
package/src/launch.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { spawn, spawnSync } from "node:child_process"
2
2
 
3
3
  import { broadcastRun } from "./daemon.js"
4
- import { BODY_ENCODING, startGatewayProxy } from "./gateway-proxy.js"
4
+ import { BODY_ENCODING, ORCHESTRA_ALIAS, startGatewayProxy } from "./gateway-proxy.js"
5
5
  import { BASE_PATH, models } from "./api.js"
6
- import { DEFAULT_MODE, modeEnv } from "./modes.js"
6
+ import { applyWorkforce, DEFAULT_MODE, modeEnv } from "./modes.js"
7
7
  import { CLIENT_VERSION, DSH_BIN, kriyaHome } from "./paths.js"
8
8
  import { ensureProfile } from "./profiles.js"
9
9
 
@@ -40,7 +40,9 @@ export async function planTiers(device, list = models) {
40
40
  // Harness 2.0 W2: the owner's head and worker levels, only if both are offered and differ
41
41
  const o = answer.orchestra
42
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 }
43
+ // Harness 2.0: the owner turned the workforce on for this device (Kriya's harness.workforce)
44
+ const workforce = answer.workforce === 1
45
+ 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 }), ...(workforce && { workforce }) } : { ...all, encodings }
44
46
  } catch {
45
47
  // Kriya answers the first request with the reason if it's refused
46
48
  return all
@@ -99,7 +101,13 @@ export async function startTier(device, list = models) {
99
101
  }
100
102
 
101
103
  /** @param {{ url: string, token: string } | null} device */
102
- export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = [], orchestra) {
104
+ /** The picker's name for the Orchestration choice: which model leads and which builds. */
105
+ export function orchestraName(orchestra, names = {}) {
106
+ const plain = (tier) => String(names[tier] ?? `Kriya ${tier}`).replace(/ · (budget|balanced|escalation)$/, "")
107
+ return `Orchestration · ${plain(orchestra.head)} leads, ${plain(orchestra.worker)} builds`.slice(0, 120)
108
+ }
109
+
110
+ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = [], orchestra, pick = false) {
103
111
  const env = {
104
112
  ...base,
105
113
  // The mode always comes from `--mode` (or the default), never the shell
@@ -121,9 +129,18 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
121
129
  // Harness 2.0 W2: the head and worker levels come only from Kriya's GET /models, never the shell
122
130
  delete env.KRIYA_ORCHESTRA_HEAD
123
131
  delete env.KRIYA_ORCHESTRA_WORKER
132
+ delete env.KRIYA_ORCHESTRA_PICK
133
+ delete env.KRIYA_ORCHESTRA_NAME
124
134
  if (orchestra && START_TIERS.includes(orchestra.head) && START_TIERS.includes(orchestra.worker)) {
125
135
  env.KRIYA_ORCHESTRA_HEAD = orchestra.head
126
136
  env.KRIYA_ORCHESTRA_WORKER = orchestra.worker
137
+ // The picker's own "Orchestration" choice (only through the local relay, which turns it into the head tier):
138
+ // sessions start on it, and picking a single model instead runs everything on that one model
139
+ if (pick) {
140
+ env.KRIYA_ORCHESTRA_PICK = ORCHESTRA_ALIAS
141
+ env.KRIYA_ORCHESTRA_NAME = orchestraName(orchestra, names)
142
+ env.KRIYA_START_TIER = ORCHESTRA_ALIAS
143
+ }
127
144
  }
128
145
  // A token from the person's environment never stands in for the sign-in
129
146
  delete env[TOKEN_ENV]
@@ -247,6 +264,9 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
247
264
  ensureProfile(profile)
248
265
  const headless = profile === "kriya-run"
249
266
  const tiers = await planTiers(device)
267
+ // Harness 2.0: the owner's switches, where the person set none of their own (src/modes.js applyWorkforce)
268
+ const turned = applyWorkforce(process.env, tiers.workforce)
269
+ if (turned.length) process.stderr.write(`kriya: Harness 2.0 is on from your Kriya owner settings: ${turned.join(", ")}. Turn one off with --no-<name>, e.g. --no-${turned[0]}.\n`)
250
270
  // Harness 2.0 W2: with --orchestra and Kriya's offer, the session itself runs on the head level
251
271
  const orchestra = process.env.KRIYA_ORCHESTRA === "on" && process.env.KRIYA_LOOP === "on" ? tiers.orchestra : undefined
252
272
  // DSH and the Kriya plugins reach Kriya through the local relay
@@ -257,6 +277,8 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
257
277
  ? await startGatewayProxy({
258
278
  target: device.url,
259
279
  encode: tiers.encodings.includes(BODY_ENCODING),
280
+ // Harness 2.0: the picker's Orchestration choice reaches Kriya as the head tier
281
+ ...(orchestra && { aliases: { [ORCHESTRA_ALIAS]: orchestra.head } }),
260
282
  // A Kriya deployed after launch is picked up without a restart
261
283
  checkSupport: async () => ((await models(device.url, device.token)).bodyEncodings ?? []).includes(BODY_ENCODING),
262
284
  log: (text) => process.stderr.write(`kriya: ${text}\n`),
@@ -274,7 +296,7 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
274
296
  // stdout: the answer (kriya run) and ACP's protocol frames pass untouched;
275
297
  // the Web UI's stdout carries only log lines, rebranded like stderr
276
298
  stdio: ["inherit", profile === "kriya" ? "pipe" : "inherit", "pipe"],
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),
299
+ 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, Boolean(relay)),
278
300
  })
279
301
  let explained = null
280
302
  const filter = htmlFilter((text) => process.stderr.write(rebrand(text)))
package/src/modes.js CHANGED
@@ -144,17 +144,52 @@ export const SWITCHES = [
144
144
  ["edit", "KRIYA_EDIT", false],
145
145
  ]
146
146
 
147
+ /** The launch variable naming the switches the person set themself (a flag, or the variable in their shell) */
148
+ export const SET_BY_PERSON = "KRIYA_SWITCHES_SET"
149
+
147
150
  /** Takes the switch flags out of `args` and sets each switch to "on" or "off" in `env`. */
148
151
  export function switchEnv(args, env = process.env) {
152
+ const chosen = new Set((env[SET_BY_PERSON] ?? "").split(",").filter(Boolean))
149
153
  for (const [flag, name, byDefault] of SWITCHES) {
154
+ if (env[name] === "on" || env[name] === "off") chosen.add(flag)
150
155
  let value = env[name] === "on" ? true : env[name] === "off" ? false : byDefault
151
156
  for (const [form, on] of [[`--${flag}`, true], [`--no-${flag}`, false]]) {
152
157
  const at = args.indexOf(form)
153
158
  if (at === -1) continue
154
159
  args.splice(at, 1)
155
160
  value = on
161
+ chosen.add(flag)
156
162
  }
157
163
  env[name] = value ? "on" : "off"
158
164
  }
165
+ // Recorded once, from the first call: later calls see the defaults written above, not the person's choice
166
+ env[SET_BY_PERSON] ??= [...chosen].join(",")
167
+ }
168
+
169
+ /**
170
+ * Harness 2.0 switches the owner turns on for every device with Kriya's
171
+ * harness.workforce (GET /models `workforce: 1`). Each still yields to the
172
+ * person's own flag or variable (`kriya --no-gates`). Repository tools and
173
+ * deploys act on the person's own GitHub and hosting logins, so they stay the
174
+ * person's to turn on per device (`kriya --repo-tools --deploy`); the Editing
175
+ * Studio has its own owner switch.
176
+ */
177
+ export const WORKFORCE_SWITCHES = Object.freeze(["cartridges", "orchestra", "gates", "critic", "milestones", "grounding", "explore", "runstrip", "mcp"])
178
+
179
+ /**
180
+ * Turns on the owner's Harness 2.0 switches the person didn't set, when Kriya
181
+ * advertises them. Without the advertisement nothing changes (HT-REG).
182
+ * @returns {string[]} the switches this turned on
183
+ */
184
+ export function applyWorkforce(env = process.env, advertised = false) {
185
+ if (!advertised) return []
186
+ const chosen = new Set((env[SET_BY_PERSON] ?? "").split(",").filter(Boolean))
187
+ const turned = []
188
+ for (const [flag, name] of SWITCHES) {
189
+ if (!WORKFORCE_SWITCHES.includes(flag) || chosen.has(flag) || env[name] === "on") continue
190
+ env[name] = "on"
191
+ turned.push(flag)
192
+ }
193
+ return turned
159
194
  }
160
195
 
package/src/orchestra.js CHANGED
@@ -41,3 +41,10 @@ export function tierFor({ orchestra, attempt, previous, earlier, force = false,
41
41
  export function escalateAfterFromEnv(env = process.env) {
42
42
  return /^[0-4]$/.test(env.KRIYA_ESCALATE_AFTER ?? "") ? Number(env.KRIYA_ESCALATE_AFTER) : undefined
43
43
  }
44
+
45
+ /**
46
+ * Harness 2.0: whether a session runs split (head and worker). With the
47
+ * picker's Orchestration choice offered (`pick`), only a session whose model
48
+ * is that choice; without it, every session (the earlier behaviour).
49
+ */
50
+ export const sessionOrchestrated = (levels, pick, model) => Boolean(levels) && (!pick || model === pick)