@kriya-ai/harness 2.0.0 → 2.1.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.
@@ -75,6 +75,89 @@ 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
+
96
+ // S-1 and own models (src/local-model.js, src/own-models.js): a chat request
97
+ // for a routed model id (`local`, `own-N`) goes to that model's own endpoint,
98
+ // with its real model name; nothing else goes there, and Kriya never sees it
99
+ export const LOCAL_MODEL = "local"
100
+ /** { route, body } for a routed model's chat request, else null */
101
+ export function routedBody(body, path, headers, routes) {
102
+ if (!routes || !body || !path.endsWith("/chat/completions") || !/^application\/json\b/i.test(headers["content-type"] ?? "")) return null
103
+ const text = body.toString("utf8")
104
+ if (!Object.keys(routes).some((id) => text.includes(`"${id}"`))) return null
105
+ let value
106
+ try {
107
+ value = JSON.parse(text)
108
+ } catch {
109
+ return null
110
+ }
111
+ const route = typeof value?.model === "string" && Object.hasOwn(routes, value.model) ? routes[value.model] : null
112
+ if (!route) return null
113
+ // OpenAI-compatible streams carry token counts only when asked; OpenRouter adds its cost to them
114
+ const counted = value.stream ? { stream_options: { ...(value.stream_options ?? {}), include_usage: true } } : {}
115
+ return { route, body: Buffer.from(JSON.stringify({ ...value, ...counted, model: route.model })) }
116
+ }
117
+ /** The S-1 shape, kept for its callers */
118
+ export const localBody = (body, path, headers, local) => routedBody(body, path, headers, local ? { [LOCAL_MODEL]: local } : null)?.body ?? null
119
+
120
+ /** Token counts (and a provider's own cost, in micro-USD) from the end of an answer: JSON or an SSE stream */
121
+ export function usageOf(tail) {
122
+ const candidates = []
123
+ for (const line of String(tail).split("\n").reverse()) {
124
+ const text = line.startsWith("data:") ? line.slice(5).trim() : line.trim()
125
+ if (text.startsWith("{") && /"usage"\s*:\s*\{/.test(text)) candidates.push(text)
126
+ }
127
+ if (!candidates.length && String(tail).trim().startsWith("{")) candidates.push(String(tail).trim())
128
+ for (const text of candidates) {
129
+ let value
130
+ try {
131
+ value = JSON.parse(text)
132
+ } catch {
133
+ continue
134
+ }
135
+ // Groq puts a stream's figures under x_groq
136
+ const u = value?.usage ?? value?.x_groq?.usage
137
+ if (!u || typeof u !== "object") continue
138
+ const int = (n) => (Number.isSafeInteger(n) && n >= 0 ? n : 0)
139
+ const cost = typeof u.cost === "number" && Number.isFinite(u.cost) && u.cost >= 0 ? Math.round(u.cost * 1_000_000) : undefined
140
+ return { inputTokens: int(u.prompt_tokens), outputTokens: int(u.completion_tokens), ...(cost !== undefined && { reportedCostMicroUsd: cost }) }
141
+ }
142
+ return null
143
+ }
144
+
145
+ const TAIL = 256 * 1024
146
+ /** Passes an answer through untouched, keeping its tail to read the usage when it ends */
147
+ function counting(onEnd) {
148
+ const decoder = new TextDecoder()
149
+ let tail = ""
150
+ return new TransformStream({
151
+ transform(chunk, controller) {
152
+ tail = (tail + decoder.decode(chunk, { stream: true })).slice(-TAIL)
153
+ controller.enqueue(chunk)
154
+ },
155
+ flush() {
156
+ onEnd(usageOf(tail + decoder.decode()))
157
+ },
158
+ })
159
+ }
160
+
78
161
  /**
79
162
  * Starts the relay in front of `target` (the signed-in Kriya's address).
80
163
  * `encode`: whether Kriya decodes encoded bodies, as known at launch.
@@ -87,9 +170,11 @@ async function readAll(req) {
87
170
  * @param {{ target: string, encode: boolean, checkSupport?: () => Promise<boolean>, fetchImpl?: typeof fetch, log?: (text: string) => void, now?: () => number, retryMs?: number }} options
88
171
  * @returns {Promise<{ url: string, close: () => Promise<void>, encoding: () => boolean }>} url stands in for device.url inside DSH
89
172
  */
90
- export async function startGatewayProxy({ target, encode, checkSupport, fetchImpl = fetch, log = () => {}, now = Date.now, retryMs = RETRY_MS, outageMs = OUTAGE_MS, outageWaitMs = OUTAGE_WAIT_MS }) {
173
+ export async function startGatewayProxy({ target, encode, checkSupport, aliases = {}, local = null, routes = null, onUsage = () => {}, fetchImpl = fetch, log = () => {}, now = Date.now, retryMs = RETRY_MS, outageMs = OUTAGE_MS, outageWaitMs = OUTAGE_WAIT_MS }) {
91
174
  const origin = new URL(target).origin
92
175
  const support = { on: Boolean(encode), checked: now(), pending: null }
176
+ // Routed models: the person's own (with their key) and S-1's local model (without one)
177
+ const table = { ...(routes ?? {}), ...(local && { [LOCAL_MODEL]: { ...local, provider: "local" } }) }
93
178
  // One question at a time; a failed question changes nothing
94
179
  const recheck = () => {
95
180
  if (support.on || !checkSupport) return Promise.resolve(support.on)
@@ -121,7 +206,46 @@ export async function startGatewayProxy({ target, encode, checkSupport, fetchImp
121
206
  if (body === null) return error(413, "This request is larger than Kriya Harness sends (64 MB).")
122
207
  const headers = {}
123
208
  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
209
+ // The picker's Orchestration alias first: its head may itself be a routed model
210
+ const plain = aliased(body?.length ? body : undefined, path, headers, aliases)
211
+ const routed = routedBody(plain, path, headers, Object.keys(table).length ? table : null)
212
+ if (routed) {
213
+ const { route } = routed
214
+ const local = route.provider === "local"
215
+ // Only the body, its type and the person's own key for that provider: never the device token or Kriya's headers
216
+ let answer
217
+ const send = (payload) =>
218
+ fetchImpl(`${route.url}/chat/completions`, {
219
+ method: "POST",
220
+ headers: { "content-type": "application/json", accept: headers.accept ?? "*/*", ...(route.key && { authorization: `Bearer ${route.key}` }) },
221
+ body: payload,
222
+ signal: upstream.signal,
223
+ redirect: "error",
224
+ })
225
+ try {
226
+ answer = await send(routed.body)
227
+ // A provider that refuses stream_options: once more without it (a refused request generated nothing)
228
+ if ((answer.status === 400 || answer.status === 422) && routed.body.includes('"stream_options"')) {
229
+ const value = JSON.parse(routed.body.toString("utf8"))
230
+ delete value.stream_options
231
+ await answer.body?.cancel().catch(() => {})
232
+ answer = await send(Buffer.from(JSON.stringify(value)))
233
+ }
234
+ } catch (e) {
235
+ if (e?.name === "AbortError") return
236
+ log(`relay: ${local ? "the local model server" : route.provider} didn't answer (${e?.cause?.code ?? e?.name ?? "error"})`)
237
+ return error(502, local ? `Your local model server at ${route.url} isn't answering; start it again, or restart kriya without --local-model.` : `${new URL(route.url).host} isn't answering; try again, or choose another model.`)
238
+ }
239
+ const out = {}
240
+ answer.headers.forEach((value, name) => {
241
+ if (!DROP_RESPONSE.has(name)) out[name] = value
242
+ })
243
+ res.writeHead(answer.status, out)
244
+ if (!answer.body) return res.end()
245
+ // Counts only, from the answer's own usage figures: never its text
246
+ const counted = answer.ok ? answer.body.pipeThrough(counting((u) => onUsage({ provider: route.provider, model: route.model, requests: 1, inputTokens: u?.inputTokens ?? 0, outputTokens: u?.outputTokens ?? 0, ...(u?.reportedCostMicroUsd !== undefined && { reportedCostMicroUsd: u.reportedCostMicroUsd }) }))) : answer.body
247
+ return await pipeline(Readable.fromWeb(counted), res)
248
+ }
125
249
  const encodable = Boolean(plain) && /^application\/json\b/i.test(headers["content-type"] ?? "")
126
250
  if (encodable && !support.on && now() - support.checked >= RECHECK_MS) await recheck()
127
251
  const once = (encoded) => {
package/src/launch.js CHANGED
@@ -1,9 +1,12 @@
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, SET_BY_PERSON } from "./modes.js"
7
+ import { LOCAL_WORKER, localWorker } from "./local-model.js"
8
+ import { launchOwn, ownFile, readOwn } from "./own-models.js"
9
+ import { usageReporter } from "./own-usage.js"
7
10
  import { CLIENT_VERSION, DSH_BIN, kriyaHome } from "./paths.js"
8
11
  import { ensureProfile } from "./profiles.js"
9
12
 
@@ -40,7 +43,15 @@ export async function planTiers(device, list = models) {
40
43
  // Harness 2.0 W2: the owner's head and worker levels, only if both are offered and differ
41
44
  const o = answer.orchestra
42
45
  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 }
46
+ // Harness 2.0: the owner turned the workforce on for this device (Kriya's harness.workforce)
47
+ const workforce = answer.workforce === 1
48
+ // S-1: the owner offers local models (Kriya's harness.localModels)
49
+ const localModels = answer.localModels === 1
50
+ // The owner's Developer tab (Kriya's harness.cockpit)
51
+ const cockpit = answer.cockpit === 1
52
+ // Own models: the person may use their own keys and orchestration (Kriya's harness.ownModels)
53
+ const ownModels = answer.ownModels === 1
54
+ 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 }), ...(localModels && { localModels }), ...(cockpit && { cockpit }), ...(ownModels && { ownModels }) } : { ...all, encodings }
44
55
  } catch {
45
56
  // Kriya answers the first request with the reason if it's refused
46
57
  return all
@@ -99,7 +110,23 @@ export async function startTier(device, list = models) {
99
110
  }
100
111
 
101
112
  /** @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) {
113
+ /** The picker's name for the Orchestration choice: which model leads and which builds. */
114
+ export function orchestraName(orchestra, names = {}) {
115
+ const plain = (tier) => String(names[tier] ?? `Kriya ${tier}`).replace(/ · (budget|balanced|escalation)$/, "")
116
+ return `Orchestration · ${plain(orchestra.head)} leads, ${plain(orchestra.worker)} builds`.slice(0, 120)
117
+ }
118
+
119
+ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = [], orchestra, pick = false, local = null, own = null) {
120
+ // Own models (src/own-models.js): ids, names and windows only; keys stay in the launcher's relay
121
+ const ownModels = pick && own?.models?.length ? own.models : []
122
+ const ownIds = ownModels.map((m) => m.id)
123
+ // The person's own orchestration, when it's the one chosen (and the relay that routes it is on)
124
+ const personal = Boolean(pick && own?.orchestra && orchestra === own.orchestra)
125
+ // S-1: a found local server builds as the owner's orchestra's worker; in the person's own, only where they chose it
126
+ const localOn = Boolean(local && orchestra && pick && (!personal || orchestra.worker === LOCAL_WORKER))
127
+ const levels = personal ? orchestra : localOn ? { ...orchestra, worker: LOCAL_WORKER } : orchestra
128
+ const named = { ...names, ...(localOn && { [LOCAL_WORKER]: `Local · ${local.model}`.slice(0, 80) }), ...Object.fromEntries(ownModels.map((m) => [m.id, m.name])) }
129
+ const usable = (id) => START_TIERS.includes(id) || ownIds.includes(id) || (id === LOCAL_WORKER && localOn)
103
130
  const env = {
104
131
  ...base,
105
132
  // The mode always comes from `--mode` (or the default), never the shell
@@ -112,7 +139,7 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
112
139
  // Read by the kriya provider row: the models the picker offers. Never from the shell
113
140
  KRIYA_ALLOWED_TIERS: (allowed.filter((t) => START_TIERS.includes(t)).length ? allowed.filter((t) => START_TIERS.includes(t)) : START_TIERS).join(","),
114
141
  // The picker's name per tier (modelNames), as JSON. Never from the shell
115
- KRIYA_MODEL_NAMES: JSON.stringify(Object.fromEntries(Object.entries(names).filter(([t, n]) => START_TIERS.includes(t) && typeof n === "string" && n.length <= 80))),
142
+ KRIYA_MODEL_NAMES: JSON.stringify(Object.fromEntries(Object.entries(named).filter(([t, n]) => usable(t) && typeof n === "string" && n.length <= 80))),
116
143
  // Each tier's context window, output cap and compaction headroom (modelLimits), as JSON. Never from the shell
117
144
  KRIYA_MODEL_LIMITS: JSON.stringify(Object.fromEntries(Object.entries(limits).filter(([t]) => START_TIERS.includes(t)))),
118
145
  // The tiers whose model takes images, as GET /models says. Never from the shell
@@ -121,9 +148,34 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
121
148
  // Harness 2.0 W2: the head and worker levels come only from Kriya's GET /models, never the shell
122
149
  delete env.KRIYA_ORCHESTRA_HEAD
123
150
  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
151
+ delete env.KRIYA_ORCHESTRA_PICK
152
+ delete env.KRIYA_ORCHESTRA_NAME
153
+ delete env.KRIYA_LOCAL_MODEL_ID
154
+ delete env.KRIYA_LOCAL_MODEL_LABEL
155
+ delete env.KRIYA_OWN_MODELS
156
+ delete env.KRIYA_OWN_MODEL_IDS
157
+ delete env.KRIYA_KEY_HASHES
158
+ if (ownModels.length) {
159
+ // The picker's extra models and their windows (no key, no address), and the key hashes DSH redacts by
160
+ env.KRIYA_OWN_MODELS = JSON.stringify(ownModels.map((m) => ({ id: m.id, name: m.name, contextWindow: m.contextWindow })))
161
+ env.KRIYA_OWN_MODEL_IDS = ownIds.join(",")
162
+ if (own.hashes?.length) env.KRIYA_KEY_HASHES = own.hashes.join(",")
163
+ }
164
+ const valid = personal ? usable(levels.head) && usable(levels.worker) && levels.head !== levels.worker : orchestra && START_TIERS.includes(orchestra.head) && START_TIERS.includes(orchestra.worker)
165
+ if (orchestra && valid) {
166
+ env.KRIYA_ORCHESTRA_HEAD = levels.head
167
+ env.KRIYA_ORCHESTRA_WORKER = levels.worker
168
+ if (localOn && levels.worker === LOCAL_WORKER) {
169
+ env.KRIYA_LOCAL_MODEL_ID = local.model
170
+ env.KRIYA_LOCAL_MODEL_LABEL = named[LOCAL_WORKER]
171
+ }
172
+ // The picker's own "Orchestration" choice (only through the local relay, which turns it into the head tier):
173
+ // sessions start on it, and picking a single model instead runs everything on that one model
174
+ if (pick) {
175
+ env.KRIYA_ORCHESTRA_PICK = ORCHESTRA_ALIAS
176
+ env.KRIYA_ORCHESTRA_NAME = orchestraName(levels, named)
177
+ env.KRIYA_START_TIER = ORCHESTRA_ALIAS
178
+ }
127
179
  }
128
180
  // A token from the person's environment never stands in for the sign-in
129
181
  delete env[TOKEN_ENV]
@@ -247,16 +299,52 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
247
299
  ensureProfile(profile)
248
300
  const headless = profile === "kriya-run"
249
301
  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
302
+ // Harness 2.0: the owner's switches, where the person set none of their own (src/modes.js applyWorkforce)
303
+ const turned = applyWorkforce(process.env, tiers.workforce)
304
+ // The Developer tab from the owner's settings, unless the person said --no-cockpit
305
+ if (tiers.cockpit && !(process.env[SET_BY_PERSON] ?? "").split(",").includes("cockpit")) process.env.KRIYA_COCKPIT = "on"
306
+ 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`)
307
+ const relayOn = Boolean(device) && process.env.KRIYA_RELAY !== "off"
308
+ // Own models (src/own-models.js): the person's keys and orchestration, with the owner's
309
+ // harness.ownModels and the relay that routes them; keys stay in this process
310
+ const own = tiers.ownModels && relayOn ? launchOwn(ownFile(), { allowed: tiers.allowed, local: true }) : null
311
+ if (tiers.ownModels && !relayOn && readOwn().models.length) process.stderr.write("kriya: your own models need the local relay (KRIYA_RELAY=off turns it off); using Kriya's models.\n")
312
+ const personChose = (process.env[SET_BY_PERSON] ?? "").split(",")
313
+ // Their orchestration from the Developer tab counts as their choice, under any --no-orchestra of theirs
314
+ if (own?.orchestra && !personChose.includes("orchestra")) process.env.KRIYA_ORCHESTRA = "on"
315
+ if (own?.orchestra?.worker === LOCAL_WORKER && !process.env.KRIYA_LOCAL_MODEL) process.env.KRIYA_LOCAL_MODEL = "on"
316
+ // Harness 2.0 W2: with the orchestra on, the session itself runs on the head level: the person's own, else Kriya's offer
317
+ const orchestrating = process.env.KRIYA_ORCHESTRA === "on" && process.env.KRIYA_LOOP === "on"
318
+ let orchestra = orchestrating ? (own?.orchestra ?? tiers.orchestra) : undefined
319
+ // S-1: `--local-model`, with the owner's offer, the orchestra and the relay (which sends the local model's requests)
320
+ const { local, note } = await localWorker(process.env, { offered: Boolean(tiers.localModels) && relayOn, orchestra })
321
+ if (note) process.stderr.write(`kriya: ${note}\n`)
322
+ if (orchestra && orchestra === own?.orchestra && orchestra.worker === LOCAL_WORKER && !local) {
323
+ process.stderr.write("kriya: your orchestration builds on the local model, which isn't available now; using Kriya's orchestration instead.\n")
324
+ orchestra = tiers.orchestra
325
+ }
326
+ if (orchestra && orchestra === own?.orchestra) {
327
+ const name = (id) => own.models.find((m) => m.id === id)?.name ?? (id === LOCAL_WORKER ? `Local · ${local?.model}` : tiers.names?.[id] ?? `Kriya ${id}`)
328
+ process.stderr.write(`kriya: your orchestration: ${name(orchestra.head)} leads, ${name(orchestra.worker)} builds.\n`)
329
+ }
330
+ // What the Developer tab may offer (plugins/cockpit): from Kriya's advert only, never the shell
331
+ process.env.KRIYA_OWN_MODELS_OFFER = tiers.ownModels && relayOn ? "on" : "off"
332
+ process.env.KRIYA_LOCAL_MODELS_OFFER = tiers.localModels && relayOn ? "on" : "off"
333
+ // Counts of own-key and local calls for Kriya (src/own-usage.js); never content or keys
334
+ const reporter = own ? usageReporter({ device, log: (text) => process.stderr.write(`kriya: ${text}\n`) }) : null
252
335
  // DSH and the Kriya plugins reach Kriya through the local relay
253
336
  // (src/gateway-proxy.js): encoded bodies past the host's firewall, and a
254
337
  // block said as such. KRIYA_RELAY=off talks to Kriya directly, as before
255
338
  const relay =
256
- device && process.env.KRIYA_RELAY !== "off"
339
+ relayOn
257
340
  ? await startGatewayProxy({
258
341
  target: device.url,
259
342
  encode: tiers.encodings.includes(BODY_ENCODING),
343
+ // Harness 2.0: the picker's Orchestration choice reaches Kriya as the head tier
344
+ ...(orchestra && { aliases: { [ORCHESTRA_ALIAS]: orchestra.head } }),
345
+ ...(local && { local }),
346
+ ...(own && { routes: own.routes }),
347
+ ...(reporter && { onUsage: reporter.add }),
260
348
  // A Kriya deployed after launch is picked up without a restart
261
349
  checkSupport: async () => ((await models(device.url, device.token)).bodyEncodings ?? []).includes(BODY_ENCODING),
262
350
  log: (text) => process.stderr.write(`kriya: ${text}\n`),
@@ -274,7 +362,7 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
274
362
  // stdout: the answer (kriya run) and ACP's protocol frames pass untouched;
275
363
  // the Web UI's stdout carries only log lines, rebranded like stderr
276
364
  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),
365
+ 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), local ?? null, own),
278
366
  })
279
367
  let explained = null
280
368
  const filter = htmlFilter((text) => process.stderr.write(rebrand(text)))
@@ -307,7 +395,8 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
307
395
  filter.end()
308
396
  explained ??= filter.explained
309
397
  if (explained) process.stderr.write(`kriya: ${explained}\n`)
310
- ended.finally(() => done(code ?? (signal ? 1 : 0)))
398
+ // The last own-model counts go before kriya exits (best effort)
399
+ Promise.allSettled([ended, reporter?.close()]).finally(() => done(code ?? (signal ? 1 : 0)))
311
400
  })
312
401
  })
313
402
  }
@@ -0,0 +1,110 @@
1
+ // S-1 local models (Kriya-Tavi docs/kriya-harness/LOCAL_MODELS.md; owner
2
+ // decision SI-01, 2026-11-24): with the owner's harness.localModels and
3
+ // `kriya --local-model`, a model on this computer or the person's own network
4
+ // (Ollama, LM Studio, vLLM: any OpenAI-compatible server) builds the
5
+ // orchestra's worker steps. Kriya's head still plans, reviews and takes over;
6
+ // the person stays signed in. Only loopback and private addresses: code never
7
+ // goes to a public host this way. The relay (src/gateway-proxy.js) sends the
8
+ // `local` model's requests there, without the Kriya device token.
9
+
10
+ import { isIP } from "node:net"
11
+
12
+ /** The model id DSH and the loop use for the local worker; never a Kriya tier */
13
+ export const LOCAL_WORKER = "local"
14
+
15
+ /** Where a local server usually answers: Ollama, then LM Studio */
16
+ export const KNOWN_SERVERS = [
17
+ { name: "Ollama", url: "http://127.0.0.1:11434/v1" },
18
+ { name: "LM Studio", url: "http://127.0.0.1:1234/v1" },
19
+ ]
20
+
21
+ export const PROBE_MS = 1500
22
+ // Ollama serves 4,096 tokens unless told otherwise (OLLAMA_CONTEXT_LENGTH); a builder needs more
23
+ export const DEFAULT_CONTEXT = 32_768
24
+ const MODEL_ID = /^[\w.:\/@+-]{1,120}$/
25
+
26
+ /** Loopback, private (RFC 1918, IPv6 ULA) or a .local name: the person's own computer or network */
27
+ export function isLocalAddress(value) {
28
+ let url
29
+ try {
30
+ url = new URL(value)
31
+ } catch {
32
+ return false
33
+ }
34
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false
35
+ if (url.username || url.password) return false
36
+ const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase()
37
+ if (host === "localhost" || host.endsWith(".local")) return true
38
+ if (isIP(host) === 4) {
39
+ const [a, b] = host.split(".").map(Number)
40
+ return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168)
41
+ }
42
+ if (isIP(host) === 6) return host === "::1" || /^f[cd][0-9a-f]{2}:/.test(host)
43
+ return false
44
+ }
45
+
46
+ /** The model to use: the one named (only if served), else the first "coder", else the first */
47
+ export function chooseModel(ids, wanted) {
48
+ const served = ids.filter((id) => typeof id === "string" && MODEL_ID.test(id))
49
+ if (wanted) return served.includes(wanted) ? wanted : null
50
+ return served.find((id) => /coder/i.test(id)) ?? served[0] ?? null
51
+ }
52
+
53
+ /**
54
+ * Finds the local server and its model. `url` from the person, else the known servers in turn.
55
+ * @returns {Promise<{ url: string, model: string, server: string } | { error: string }>}
56
+ */
57
+ export async function findLocalModel({ url, name, fetchImpl = fetch, timeoutMs = PROBE_MS } = {}) {
58
+ const candidates = url ? [{ name: "your server", url: url.replace(/\/+$/, "") }] : KNOWN_SERVERS
59
+ if (url && !isLocalAddress(url)) return { error: `${url} isn't on this computer or a private network; --local-model takes a loopback or private address only.` }
60
+ for (const candidate of candidates) {
61
+ let ids
62
+ try {
63
+ const answer = await fetchImpl(`${candidate.url}/models`, { signal: AbortSignal.timeout(timeoutMs), redirect: "error" })
64
+ if (!answer.ok) continue
65
+ const body = await answer.json()
66
+ ids = Array.isArray(body?.data) ? body.data.map((m) => m?.id) : []
67
+ } catch {
68
+ continue
69
+ }
70
+ const model = chooseModel(ids, name)
71
+ if (model) return { url: candidate.url, model, server: candidate.name }
72
+ return { error: name ? `${candidate.name} at ${candidate.url} doesn't serve ${name}.` : `${candidate.name} at ${candidate.url} has no model yet (for Ollama: ollama pull qwen2.5-coder:14b).` }
73
+ }
74
+ return { error: url ? `Nothing answered at ${url}.` : "No local model server is running (Ollama on port 11434 or LM Studio on 1234)." }
75
+ }
76
+
77
+ /** Takes `--local-model [url]` and `--local-model-name <name>` out of `args` into `env` */
78
+ export function localModelArgs(args, env = process.env) {
79
+ const at = args.indexOf("--local-model")
80
+ if (at !== -1) {
81
+ const next = args[at + 1]
82
+ const withUrl = typeof next === "string" && /^https?:\/\//.test(next)
83
+ args.splice(at, withUrl ? 2 : 1)
84
+ env.KRIYA_LOCAL_MODEL = withUrl ? next : "on"
85
+ }
86
+ const named = args.indexOf("--local-model-name")
87
+ if (named !== -1) {
88
+ env.KRIYA_LOCAL_MODEL_NAME = args[named + 1] ?? ""
89
+ args.splice(named, 2)
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Whether and where the local worker runs for this launch: the person asked
95
+ * (KRIYA_LOCAL_MODEL), the owner offers it (GET /models `localModels: 1`), the
96
+ * orchestra is on (the local model only builds), and a server answered.
97
+ * @returns {Promise<{ local?: { url: string, model: string, server: string }, note?: string }>}
98
+ */
99
+ export async function localWorker(env, { offered, orchestra }, find = findLocalModel) {
100
+ const asked = env.KRIYA_LOCAL_MODEL
101
+ if (!asked || asked === "off") return {}
102
+ if (!offered) return { note: "local models aren't turned on for your Kriya account yet (the owner's harness.localModels); using Kriya's models." }
103
+ if (!orchestra) return { note: "a local model builds the orchestra's worker steps, and the orchestra is off; using Kriya's models." }
104
+ const found = await find({ url: asked === "on" ? undefined : asked, name: env.KRIYA_LOCAL_MODEL_NAME || undefined })
105
+ if ("error" in found) return { note: `${found.error} Using Kriya's models.` }
106
+ return {
107
+ local: found,
108
+ note: `${found.model} (${found.server}, ${found.url}) builds on this computer; Kriya's ${orchestra.head} plans, reviews and takes over when it's stuck.${found.server === "Ollama" ? " Give Ollama a 32k context: OLLAMA_CONTEXT_LENGTH=32768 ollama serve." : ""}`,
109
+ }
110
+ }
package/src/loop.js CHANGED
@@ -5,6 +5,7 @@ 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 { stepsProof } from "./proof.js"
8
9
  import { cartridgeSection } from "./cartridges.js"
9
10
  import { polishSection } from "./critic.js"
10
11
  import { directionHints, EXPLORE_ROLES, MAX_TAKES, MIN_TAKES, takeSection } from "./explore.js"
@@ -168,7 +169,9 @@ export function writeSnapshot(cwd, sessionId, { current, env = process.env } = {
168
169
  if (!env.KRIYA_PROGRESS_FILE) return
169
170
  try {
170
171
  const plan = planStatus(cwd, sessionId)?.map((s) => ({ ...s, ...(s.n === current && !s.building && { building: { attempt: s.attempts + 1 } }) }))
171
- writeFileSync(env.KRIYA_PROGRESS_FILE, JSON.stringify({ plan }))
172
+ // S-3: with Kriya's proof asked for, the code-computed verdict too (src/proof.js)
173
+ const proof = env.KRIYA_TASK_PROOF === "on" ? stepsProof(readProgress(projectRoot(cwd), sessionId), env) : undefined
174
+ writeFileSync(env.KRIYA_PROGRESS_FILE, JSON.stringify({ plan, ...(proof && { proof }) }))
172
175
  } catch {
173
176
  // The run doesn't depend on being reported
174
177
  }
package/src/modes.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { dirname, join } from "node:path"
4
+
1
5
  // Kriya Harness modes: how much the agent may do on its own. Each mode is one
2
6
  // sandbox mode and one approval policy of DeepSeek Harness, set through the
3
7
  // kriya bundle's rows (bundle/cordis.patch.yml) from the launch variables
@@ -142,19 +146,86 @@ export const SWITCHES = [
142
146
  // The Editing Studio (track E): off until the owner turns it on; off, nothing
143
147
  // under src/edit/ loads
144
148
  ["edit", "KRIYA_EDIT", false],
149
+ // The Developer tab (plugins/cockpit, Kriya-Tavi docs/kriya-harness/DEVELOPER_COCKPIT.md):
150
+ // GitHub, connections, running servers, project health; on from the owner's harness.cockpit
151
+ ["cockpit", "KRIYA_COCKPIT", false],
152
+ // Supabase and Render tools through the person's own CLIs (plugins/providers): reads free,
153
+ // writes approved; the person's per computer, like repo-tools
154
+ ["provider-tools", "KRIYA_PROVIDER_TOOLS", false],
145
155
  ]
146
156
 
157
+ /** Switches the person may turn on or off from the Developer tab, kept per computer in ~/.kriya/switches.json */
158
+ export const SAVED_SWITCHES = Object.freeze(["repo-tools", "provider-tools"])
159
+
160
+ const savedFile = () => join(process.env.KRIYA_HOME || join(homedir(), ".kriya"), "switches.json")
161
+
162
+ /** The person's saved switches ({ "repo-tools": true }); none when the file is missing or broken */
163
+ export function savedSwitches(file = savedFile()) {
164
+ try {
165
+ const value = JSON.parse(readFileSync(file, "utf8"))
166
+ return Object.fromEntries(Object.entries(value ?? {}).filter(([k, v]) => SAVED_SWITCHES.includes(k) && typeof v === "boolean"))
167
+ } catch {
168
+ return {}
169
+ }
170
+ }
171
+
172
+ /** Saves one of the person's switches for the next start of Kriya Harness */
173
+ export function saveSwitch(flag, on, file = savedFile()) {
174
+ if (!SAVED_SWITCHES.includes(flag) || typeof on !== "boolean") throw new Error(`${flag} can't be saved.`)
175
+ const next = { ...savedSwitches(file), [flag]: on }
176
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
177
+ writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
178
+ return next
179
+ }
180
+
181
+ /** The launch variable naming the switches the person set themself (a flag, or the variable in their shell) */
182
+ export const SET_BY_PERSON = "KRIYA_SWITCHES_SET"
183
+
147
184
  /** Takes the switch flags out of `args` and sets each switch to "on" or "off" in `env`. */
148
- export function switchEnv(args, env = process.env) {
185
+ export function switchEnv(args, env = process.env, saved = savedSwitches()) {
186
+ const chosen = new Set((env[SET_BY_PERSON] ?? "").split(",").filter(Boolean))
149
187
  for (const [flag, name, byDefault] of SWITCHES) {
188
+ // The person's choice from the Developer tab, under any flag or variable of theirs
189
+ if (env[name] !== "on" && env[name] !== "off" && SAVED_SWITCHES.includes(flag) && typeof saved[flag] === "boolean") env[name] = saved[flag] ? "on" : "off"
190
+ if (env[name] === "on" || env[name] === "off") chosen.add(flag)
150
191
  let value = env[name] === "on" ? true : env[name] === "off" ? false : byDefault
151
192
  for (const [form, on] of [[`--${flag}`, true], [`--no-${flag}`, false]]) {
152
193
  const at = args.indexOf(form)
153
194
  if (at === -1) continue
154
195
  args.splice(at, 1)
155
196
  value = on
197
+ chosen.add(flag)
156
198
  }
157
199
  env[name] = value ? "on" : "off"
158
200
  }
201
+ // Recorded once, from the first call: later calls see the defaults written above, not the person's choice
202
+ env[SET_BY_PERSON] ??= [...chosen].join(",")
203
+ }
204
+
205
+ /**
206
+ * Harness 2.0 switches the owner turns on for every device with Kriya's
207
+ * harness.workforce (GET /models `workforce: 1`). Each still yields to the
208
+ * person's own flag or variable (`kriya --no-gates`). Repository tools and
209
+ * deploys act on the person's own GitHub and hosting logins, so they stay the
210
+ * person's to turn on per device (`kriya --repo-tools --deploy`); the Editing
211
+ * Studio has its own owner switch.
212
+ */
213
+ export const WORKFORCE_SWITCHES = Object.freeze(["cartridges", "orchestra", "gates", "critic", "milestones", "grounding", "explore", "runstrip", "mcp"])
214
+
215
+ /**
216
+ * Turns on the owner's Harness 2.0 switches the person didn't set, when Kriya
217
+ * advertises them. Without the advertisement nothing changes (HT-REG).
218
+ * @returns {string[]} the switches this turned on
219
+ */
220
+ export function applyWorkforce(env = process.env, advertised = false) {
221
+ if (!advertised) return []
222
+ const chosen = new Set((env[SET_BY_PERSON] ?? "").split(",").filter(Boolean))
223
+ const turned = []
224
+ for (const [flag, name] of SWITCHES) {
225
+ if (!WORKFORCE_SWITCHES.includes(flag) || chosen.has(flag) || env[name] === "on") continue
226
+ env[name] = "on"
227
+ turned.push(flag)
228
+ }
229
+ return turned
159
230
  }
160
231
 
package/src/orchestra.js CHANGED
@@ -7,6 +7,8 @@
7
7
  // --orchestra (KRIYA_ORCHESTRA=on) and Kriya offered both levels (GET /models
8
8
  // `orchestra`); otherwise every builder runs on the session's own level, as before.
9
9
 
10
+ import { LOCAL_WORKER } from "./local-model.js"
11
+
10
12
  export const DEFAULT_ESCALATE_AFTER = 2
11
13
 
12
14
  /** The head and worker levels for this process, or undefined: only aliases the plan allows, never from the shell alone. */
@@ -15,7 +17,12 @@ export function orchestraFromEnv(env = process.env) {
15
17
  const allowed = String(env.KRIYA_ALLOWED_TIERS ?? "").split(",").filter(Boolean)
16
18
  const head = env.KRIYA_ORCHESTRA_HEAD
17
19
  const worker = env.KRIYA_ORCHESTRA_WORKER
18
- if (!head || !worker || head === worker || !allowed.includes(head) || !allowed.includes(worker)) return undefined
20
+ // S-1: the local worker (src/local-model.js), only when the launcher found its server
21
+ const local = worker === LOCAL_WORKER && Boolean(env.KRIYA_LOCAL_MODEL_ID)
22
+ // Own models (src/own-models.js): the person's own, as the launcher listed them
23
+ const own = String(env.KRIYA_OWN_MODEL_IDS ?? "").split(",").filter(Boolean)
24
+ const level = (id) => allowed.includes(id) || own.includes(id)
25
+ if (!head || !worker || head === worker || !level(head) || !(local || level(worker))) return undefined
19
26
  return { head, worker }
20
27
  }
21
28
 
@@ -41,3 +48,10 @@ export function tierFor({ orchestra, attempt, previous, earlier, force = false,
41
48
  export function escalateAfterFromEnv(env = process.env) {
42
49
  return /^[0-4]$/.test(env.KRIYA_ESCALATE_AFTER ?? "") ? Number(env.KRIYA_ESCALATE_AFTER) : undefined
43
50
  }
51
+
52
+ /**
53
+ * Harness 2.0: whether a session runs split (head and worker). With the
54
+ * picker's Orchestration choice offered (`pick`), only a session whose model
55
+ * is that choice; without it, every session (the earlier behaviour).
56
+ */
57
+ export const sessionOrchestrated = (levels, pick, model) => Boolean(levels) && (!pick || model === pick)