@kriya-ai/harness 2.0.1 → 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.
package/src/cockpit.js ADDED
@@ -0,0 +1,223 @@
1
+ import { execFile, spawn } from "node:child_process"
2
+ import { appendFileSync, existsSync, readFileSync, realpathSync } from "node:fs"
3
+ import { join, relative, sep } from "node:path"
4
+
5
+ import { confirmedCheck } from "./verify.js"
6
+
7
+ // The Developer tab's data and actions (plugins/cockpit; Kriya-Tavi
8
+ // docs/kriya-harness/DEVELOPER_COCKPIT.md). Connections are each provider's
9
+ // own CLI and the person's own login there: Kriya runs fixed argv (execFile,
10
+ // never a shell), never reads a token or a credential file, and never types a
11
+ // login code. Secrets are found by file name only; no value is read.
12
+
13
+ export class CockpitError extends Error {}
14
+
15
+ // Telemetry off and no prompts for every provider CLI Kriya runs
16
+ const QUIET = { NO_COLOR: "1", DO_NOT_TRACK: "1", RENDER_CLI_DISABLE_ANALYTICS: "1", GH_NO_UPDATE_NOTIFIER: "1", GH_PROMPT_DISABLED: "1", GIT_TERMINAL_PROMPT: "0", SUPABASE_TELEMETRY_DISABLED: "1" }
17
+
18
+ /** argv only, bounded, stdin closed. Resolves { code, stdout, stderr, missing }. */
19
+ export function runner({ env = process.env, timeoutMs = 20_000 } = {}) {
20
+ return (file, args, cwd) =>
21
+ new Promise((done) => {
22
+ const child = execFile(file, args, { cwd, env: { ...env, ...QUIET }, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) =>
23
+ done({ code: error ? (typeof error.code === "number" ? error.code : 1) : 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), missing: error?.code === "ENOENT" })
24
+ )
25
+ child.stdin?.end()
26
+ })
27
+ }
28
+
29
+ /**
30
+ * The providers the Developer tab connects through. `status` exits 0 only when
31
+ * signed in (for Render the docs don't state whoami's exit code, so a non-zero
32
+ * exit reads as "not signed in or not checked"). `login` is what the person
33
+ * runs; GitHub's is also one click (githubSignIn).
34
+ */
35
+ export const PROVIDERS = [
36
+ { id: "github", name: "GitHub", cli: "gh", version: ["--version"], status: ["auth", "status", "--hostname", "github.com"], login: "gh auth login", install: "brew install gh", docs: "https://cli.github.com" },
37
+ { id: "supabase", name: "Supabase", cli: "supabase", version: ["--version"], status: ["projects", "list", "-o", "json"], login: "supabase login", install: "brew install supabase/tap/supabase", docs: "https://supabase.com/docs/guides/cli" },
38
+ { id: "render", name: "Render", cli: "render", version: ["--version"], status: ["whoami", "-o", "json"], login: "render login", install: "brew install render", docs: "https://render.com/docs/cli" },
39
+ { id: "vercel", name: "Vercel", cli: "vercel", version: ["--version"], status: ["whoami"], login: "vercel login", install: "npm install -g vercel", docs: "https://vercel.com/docs/cli" },
40
+ ]
41
+
42
+ /** "gh version 2.103.3 (2026-10-26)" → "2.103.3" */
43
+ export const versionOf = (text) => /\b(\d+\.\d+(?:\.\d+)?)\b/.exec(String(text ?? ""))?.[1] ?? null
44
+
45
+ /** One provider's state: installed, its version, signed in (true, false), and GitHub's account name */
46
+ export async function connection(provider, run = runner()) {
47
+ const base = { id: provider.id, name: provider.name, cli: provider.cli, login: provider.login, install: provider.install, docs: provider.docs }
48
+ const v = await run(provider.cli, provider.version)
49
+ if (v.missing) return { ...base, installed: false, signedIn: false }
50
+ const s = await run(provider.cli, provider.status)
51
+ const signedIn = s.code === 0
52
+ // gh says "Logged in to github.com account <name>"; the other CLIs' account isn't parsed
53
+ const account = provider.id === "github" && signedIn ? /account\s+([A-Za-z0-9-]{1,39})\b/.exec(`${s.stdout}\n${s.stderr}`)?.[1] ?? null : null
54
+ return { ...base, installed: true, version: versionOf(v.stdout || v.stderr), signedIn, ...(account && { account }) }
55
+ }
56
+
57
+ export const connections = (run = runner()) => Promise.all(PROVIDERS.map((p) => connection(p, run)))
58
+
59
+ /**
60
+ * GitHub's one-click sign-in: `gh auth login --web`, whose one-time code the
61
+ * person enters on github.com in their browser (gh opens it). Kriya only shows
62
+ * the code gh prints for that purpose; the token stays in gh's own store.
63
+ * One at a time.
64
+ */
65
+ export function githubSignIn({ spawnImpl = spawn, env = process.env } = {}) {
66
+ let current = null
67
+ return {
68
+ // The code only while the person still needs it
69
+ state: () => (current ? { status: current.status, ...(current.status === "waiting" && { code: current.code }), ...(current.error && { error: current.error }) } : { status: "idle" }),
70
+ start() {
71
+ if (current?.status === "waiting" || current?.status === "starting") return this.state()
72
+ const child = spawnImpl("gh", ["auth", "login", "--web", "--hostname", "github.com", "--git-protocol", "https", "--skip-ssh-key"], {
73
+ env: { ...env, NO_COLOR: "1", GH_NO_UPDATE_NOTIFIER: "1" },
74
+ stdio: ["pipe", "pipe", "pipe"],
75
+ })
76
+ const run = { status: "starting", code: null, error: null, child }
77
+ current = run
78
+ let seen = ""
79
+ const read = (chunk) => {
80
+ seen = (seen + chunk).slice(-4000)
81
+ const code = /one-time code:\s*([A-Z0-9]{4}-[A-Z0-9]{4})/.exec(seen)?.[1]
82
+ if (code && !run.code) {
83
+ run.code = code
84
+ run.status = "waiting"
85
+ // gh waits for Enter before it opens the browser
86
+ child.stdin?.write("\n")
87
+ }
88
+ }
89
+ child.stdout?.on("data", read)
90
+ child.stderr?.on("data", read)
91
+ child.on("error", (e) => Object.assign(run, { status: "failed", error: e.code === "ENOENT" ? "The GitHub CLI (gh) isn't installed." : "gh couldn't start." }))
92
+ child.on("close", (exit) => {
93
+ if (run.status === "failed") return
94
+ Object.assign(run, exit === 0 ? { status: "done" } : { status: "failed", error: "GitHub sign-in didn't finish. Try again, or run gh auth login in a terminal." })
95
+ })
96
+ const timer = setTimeout(() => run.status === "waiting" || run.status === "starting" ? (child.kill("SIGTERM"), Object.assign(run, { status: "failed", error: "GitHub sign-in timed out after 10 minutes." })) : null, 10 * 60_000)
97
+ timer.unref?.()
98
+ return this.state()
99
+ },
100
+ cancel() {
101
+ if (current && (current.status === "waiting" || current.status === "starting")) {
102
+ current.child.kill("SIGTERM")
103
+ Object.assign(current, { status: "failed", error: "Canceled." })
104
+ }
105
+ return this.state()
106
+ },
107
+ }
108
+ }
109
+
110
+ /* ─────────────────────────── running servers ─────────────────────────── */
111
+
112
+ const inside = (root, path) => {
113
+ const rel = relative(root, path)
114
+ return rel === "" || (!rel.startsWith("..") && !rel.startsWith(sep) && !/^[A-Za-z]:/.test(rel))
115
+ }
116
+
117
+ /** lsof -F output → [{ pid, command, ports }] for listening TCP sockets */
118
+ export function parseListeners(text) {
119
+ const byPid = new Map()
120
+ let cur = null
121
+ for (const line of String(text ?? "").split("\n")) {
122
+ const tag = line[0]
123
+ const value = line.slice(1)
124
+ if (tag === "p") {
125
+ const pid = Number(value)
126
+ cur = byPid.get(pid) ?? { pid, command: "", ports: [] }
127
+ byPid.set(pid, cur)
128
+ } else if (tag === "c" && cur) cur.command = value.slice(0, 60)
129
+ else if (tag === "n" && cur) {
130
+ const port = Number(/:(\d+)$/.exec(value)?.[1])
131
+ if (Number.isInteger(port) && port > 0 && !cur.ports.includes(port)) cur.ports.push(port)
132
+ }
133
+ }
134
+ return [...byPid.values()].filter((p) => Number.isInteger(p.pid) && p.pid > 0 && p.ports.length)
135
+ }
136
+
137
+ /** Servers listening on TCP whose working folder is inside the project; never this process or its parent */
138
+ export async function servers(folder, run = runner({ timeoutMs: 10_000 })) {
139
+ let root
140
+ try {
141
+ root = realpathSync(folder)
142
+ } catch {
143
+ return { available: true, list: [] }
144
+ }
145
+ const all = await run("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN", "-Fpcn"])
146
+ if (all.missing) return { available: false, list: [] }
147
+ const list = []
148
+ for (const p of parseListeners(all.stdout)) {
149
+ if (p.pid === process.pid || p.pid === process.ppid) continue
150
+ const cwd = /^n(.+)$/m.exec((await run("lsof", ["-a", "-p", String(p.pid), "-d", "cwd", "-Fn"])).stdout)?.[1]
151
+ if (!cwd) continue
152
+ let real
153
+ try {
154
+ real = realpathSync(cwd)
155
+ } catch {
156
+ continue
157
+ }
158
+ if (inside(root, real)) list.push({ ...p, ports: p.ports.sort((a, b) => a - b).slice(0, 8), folder: relative(root, real) || "." })
159
+ }
160
+ return { available: true, list: list.slice(0, 20) }
161
+ }
162
+
163
+ /** Stops one listed server: only a pid the current list shows for this project */
164
+ export async function stopServer(folder, pid, run, kill = process.kill.bind(process)) {
165
+ const { list } = await servers(folder, run)
166
+ if (!list.some((s) => s.pid === pid)) throw new CockpitError("That server isn't running in this project any more.")
167
+ kill(pid, "SIGTERM")
168
+ return { stopped: pid }
169
+ }
170
+
171
+ /* ─────────────────────────── project health ─────────────────────────── */
172
+
173
+ const ENV_FILE = /(^|\/)\.env(\.[^/]*)?$/
174
+ const ENV_OK = /(^|\/)\.env\.(example|sample|template)$/
175
+ const KEY_FILE = /\.(pem|key|p12|pfx)$/
176
+
177
+ const readJson = (file) => {
178
+ try {
179
+ return JSON.parse(readFileSync(file, "utf8"))
180
+ } catch {
181
+ return null
182
+ }
183
+ }
184
+
185
+ /** What the project is, how it's checked, and secret files git would expose (names only) */
186
+ export async function health(folder, run = runner()) {
187
+ const has = (f) => existsSync(join(folder, f))
188
+ const pkg = has("package.json") ? readJson(join(folder, "package.json")) : null
189
+ const manager = has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("bun.lockb") || has("bun.lock") ? "bun" : pkg ? "npm" : null
190
+ const stack = [
191
+ pkg && { id: "node", label: `Node.js${manager ? ` · ${manager}` : ""}` },
192
+ (has("pyproject.toml") || has("requirements.txt")) && { id: "python", label: "Python" },
193
+ has("go.mod") && { id: "go", label: "Go" },
194
+ has("Cargo.toml") && { id: "rust", label: "Rust" },
195
+ has("supabase/config.toml") && { id: "supabase", label: "Supabase project" },
196
+ has("render.yaml") && { id: "render", label: "Render blueprint" },
197
+ (has("vercel.json") || has(".vercel")) && { id: "vercel", label: "Vercel project" },
198
+ ].filter(Boolean)
199
+ const scripts = pkg?.scripts && typeof pkg.scripts === "object" ? ["dev", "build", "test", "lint", "start"].filter((s) => typeof pkg.scripts[s] === "string") : []
200
+ const check = confirmedCheck(folder)
201
+ const git = await run("git", ["-C", folder, "rev-parse", "--show-toplevel"])
202
+ if (git.code !== 0) return { stack, scripts, check: check?.command ?? null, git: false, tracked: [], unignored: [] }
203
+ const root = git.stdout.trim()
204
+ const list = async (args) => (await run("git", ["-C", root, ...args])).stdout.split("\0").filter(Boolean)
205
+ const secret = (f) => (ENV_FILE.test(f) && !ENV_OK.test(f)) || KEY_FILE.test(f)
206
+ const tracked = (await list(["ls-files", "-z"])).filter(secret).slice(0, 20)
207
+ const unignored = (await list(["ls-files", "--others", "--exclude-standard", "-z"])).filter(secret).slice(0, 20)
208
+ return { stack, scripts, check: check?.command ?? null, git: true, tracked, unignored }
209
+ }
210
+
211
+ /** Adds the named, not-yet-ignored secret files to .gitignore (the person clicked it); only files health() listed */
212
+ export async function ignoreSecrets(folder, files, run = runner()) {
213
+ const { git, unignored } = await health(folder, run)
214
+ if (!git) throw new CockpitError("This folder isn't a git repository.")
215
+ const wanted = (Array.isArray(files) ? files : []).filter((f) => unignored.includes(f))
216
+ if (!wanted.length) throw new CockpitError("Those files are already ignored, or aren't secret files here.")
217
+ const root = (await run("git", ["-C", folder, "rev-parse", "--show-toplevel"])).stdout.trim()
218
+ const file = join(root, ".gitignore")
219
+ const current = existsSync(file) ? readFileSync(file, "utf8") : ""
220
+ const lines = wanted.map((f) => `/${f}`).filter((l) => !current.split("\n").includes(l))
221
+ if (lines.length) appendFileSync(file, `${current && !current.endsWith("\n") ? "\n" : ""}# Secrets (added by Kriya Harness)\n${lines.join("\n")}\n`)
222
+ return { added: lines }
223
+ }
package/src/daemon.js CHANGED
@@ -8,6 +8,7 @@ import { gzipSync } from "node:zlib"
8
8
  import { BASE_PATH, call, KriyaError, models } from "./api.js"
9
9
  import { doctor } from "./doctor.js"
10
10
  import { CLIENT_VERSION, kriyaHome } from "./paths.js"
11
+ import { baseline, changesSince } from "./proof.js"
11
12
  import { confirmRule, dismissRule, listRules } from "./rules.js"
12
13
 
13
14
  // `kriya daemon` (the Control Center, CONTROL_CENTER.md in the Kriya
@@ -294,8 +295,12 @@ export async function runDaemon(options) {
294
295
  if (running.size >= MAX_RUNNING) return refuse(`This computer is already running ${MAX_RUNNING} tasks from Kriya.`)
295
296
  await report(id, "running")
296
297
  log(`kriya daemon: task in ${folder.shown} (${payload.mode})`)
297
- const flow = payload.plan || payload.profile ? mkdtempSync(join(tmpdir(), "kriya-flow-")) : null
298
+ // S-3: Kriya asked for the proof card (harness.taskProof): live steps, the verdict, changed files
299
+ const proofOn = payload.proof === true
300
+ const flow = payload.plan || payload.profile || proofOn ? mkdtempSync(join(tmpdir(), "kriya-flow-")) : null
298
301
  const env = flow ? flowEnv(payload, flow) : {}
302
+ if (proofOn) Object.assign(env, { KRIYA_TASK_PROOF: "on", KRIYA_PROGRESS_FILE: env.KRIYA_PROGRESS_FILE ?? join(flow, "progress.json") })
303
+ const base = proofOn ? await baseline(folder.path) : null
299
304
  let sent = ""
300
305
  const beat = () => {
301
306
  const seen = env.KRIYA_PROGRESS_FILE && readProgressFile(env.KRIYA_PROGRESS_FILE)
@@ -308,6 +313,7 @@ export async function runDaemon(options) {
308
313
  const r = await child(id, runArgs(payload), folder.path, env)
309
314
  clearInterval(reporting)
310
315
  const progress = env.KRIYA_PROGRESS_FILE ? readProgressFile(env.KRIYA_PROGRESS_FILE) : null
316
+ const changes = proofOn ? await changesSince(base) : null
311
317
  if (flow) rmSync(flow, { recursive: true, force: true })
312
318
  const stopped = r.canceled
313
319
  // The answer on success; on failure the last error lines too (DSH writes the reason to stderr)
@@ -316,7 +322,8 @@ export async function runDaemon(options) {
316
322
  .filter((line) => line.trim() && !/^(dsh: warning: \d+ entries did not activate|kriya-[\w-]+ \(@kriya-ai\/[\w-]+\): pending)/.test(line))
317
323
  .join("\n")
318
324
  const answer = r.code === 0 ? r.out.trim() || errors : [r.out.trim(), errors].filter(Boolean).join("\n\n")
319
- return report(id, stopped ? "canceled" : r.code === 0 ? "done" : "failed", { exitCode: r.code, answer: tail(answer), ...(progress && { plan: progress.plan }) })
325
+ const proof = proofOn ? { ...(progress?.proof ?? {}), ...(changes && { changes }) } : null
326
+ return report(id, stopped ? "canceled" : r.code === 0 ? "done" : "failed", { exitCode: r.code, answer: tail(answer), ...(progress?.plan && { plan: progress.plan }), ...(proof && { proof }) })
320
327
  }
321
328
  if (kind === "edit") {
322
329
  if (!capabilities.edit) return report(id, "failed", { code: "not_allowed" })
@@ -93,6 +93,71 @@ export function aliased(body, path, headers, aliases) {
93
93
  return Buffer.from(JSON.stringify({ ...value, model: aliases[value.model] }))
94
94
  }
95
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
+
96
161
  /**
97
162
  * Starts the relay in front of `target` (the signed-in Kriya's address).
98
163
  * `encode`: whether Kriya decodes encoded bodies, as known at launch.
@@ -105,9 +170,11 @@ export function aliased(body, path, headers, aliases) {
105
170
  * @param {{ target: string, encode: boolean, checkSupport?: () => Promise<boolean>, fetchImpl?: typeof fetch, log?: (text: string) => void, now?: () => number, retryMs?: number }} options
106
171
  * @returns {Promise<{ url: string, close: () => Promise<void>, encoding: () => boolean }>} url stands in for device.url inside DSH
107
172
  */
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 }) {
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 }) {
109
174
  const origin = new URL(target).origin
110
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" } }) }
111
178
  // One question at a time; a failed question changes nothing
112
179
  const recheck = () => {
113
180
  if (support.on || !checkSupport) return Promise.resolve(support.on)
@@ -139,7 +206,46 @@ export async function startGatewayProxy({ target, encode, checkSupport, aliases
139
206
  if (body === null) return error(413, "This request is larger than Kriya Harness sends (64 MB).")
140
207
  const headers = {}
141
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
209
+ // The picker's Orchestration alias first: its head may itself be a routed model
142
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
+ }
143
249
  const encodable = Boolean(plain) && /^application\/json\b/i.test(headers["content-type"] ?? "")
144
250
  if (encodable && !support.on && now() - support.checked >= RECHECK_MS) await recheck()
145
251
  const once = (encoded) => {
package/src/launch.js CHANGED
@@ -3,7 +3,10 @@ import { spawn, spawnSync } from "node:child_process"
3
3
  import { broadcastRun } from "./daemon.js"
4
4
  import { BODY_ENCODING, ORCHESTRA_ALIAS, startGatewayProxy } from "./gateway-proxy.js"
5
5
  import { BASE_PATH, models } from "./api.js"
6
- import { applyWorkforce, 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
 
@@ -42,7 +45,13 @@ export async function planTiers(device, list = models) {
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
46
  // Harness 2.0: the owner turned the workforce on for this device (Kriya's harness.workforce)
44
47
  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 }
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 }
46
55
  } catch {
47
56
  // Kriya answers the first request with the reason if it's refused
48
57
  return all
@@ -107,7 +116,17 @@ export function orchestraName(orchestra, names = {}) {
107
116
  return `Orchestration · ${plain(orchestra.head)} leads, ${plain(orchestra.worker)} builds`.slice(0, 120)
108
117
  }
109
118
 
110
- export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = [], orchestra, pick = false) {
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)
111
130
  const env = {
112
131
  ...base,
113
132
  // The mode always comes from `--mode` (or the default), never the shell
@@ -120,7 +139,7 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
120
139
  // Read by the kriya provider row: the models the picker offers. Never from the shell
121
140
  KRIYA_ALLOWED_TIERS: (allowed.filter((t) => START_TIERS.includes(t)).length ? allowed.filter((t) => START_TIERS.includes(t)) : START_TIERS).join(","),
122
141
  // The picker's name per tier (modelNames), as JSON. Never from the shell
123
- 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))),
124
143
  // Each tier's context window, output cap and compaction headroom (modelLimits), as JSON. Never from the shell
125
144
  KRIYA_MODEL_LIMITS: JSON.stringify(Object.fromEntries(Object.entries(limits).filter(([t]) => START_TIERS.includes(t)))),
126
145
  // The tiers whose model takes images, as GET /models says. Never from the shell
@@ -131,14 +150,30 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
131
150
  delete env.KRIYA_ORCHESTRA_WORKER
132
151
  delete env.KRIYA_ORCHESTRA_PICK
133
152
  delete env.KRIYA_ORCHESTRA_NAME
134
- if (orchestra && START_TIERS.includes(orchestra.head) && START_TIERS.includes(orchestra.worker)) {
135
- env.KRIYA_ORCHESTRA_HEAD = orchestra.head
136
- env.KRIYA_ORCHESTRA_WORKER = orchestra.worker
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
+ }
137
172
  // The picker's own "Orchestration" choice (only through the local relay, which turns it into the head tier):
138
173
  // sessions start on it, and picking a single model instead runs everything on that one model
139
174
  if (pick) {
140
175
  env.KRIYA_ORCHESTRA_PICK = ORCHESTRA_ALIAS
141
- env.KRIYA_ORCHESTRA_NAME = orchestraName(orchestra, names)
176
+ env.KRIYA_ORCHESTRA_NAME = orchestraName(levels, named)
142
177
  env.KRIYA_START_TIER = ORCHESTRA_ALIAS
143
178
  }
144
179
  }
@@ -266,19 +301,50 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
266
301
  const tiers = await planTiers(device)
267
302
  // Harness 2.0: the owner's switches, where the person set none of their own (src/modes.js applyWorkforce)
268
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"
269
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`)
270
- // Harness 2.0 W2: with --orchestra and Kriya's offer, the session itself runs on the head level
271
- const orchestra = process.env.KRIYA_ORCHESTRA === "on" && process.env.KRIYA_LOOP === "on" ? tiers.orchestra : undefined
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
272
335
  // DSH and the Kriya plugins reach Kriya through the local relay
273
336
  // (src/gateway-proxy.js): encoded bodies past the host's firewall, and a
274
337
  // block said as such. KRIYA_RELAY=off talks to Kriya directly, as before
275
338
  const relay =
276
- device && process.env.KRIYA_RELAY !== "off"
339
+ relayOn
277
340
  ? await startGatewayProxy({
278
341
  target: device.url,
279
342
  encode: tiers.encodings.includes(BODY_ENCODING),
280
343
  // Harness 2.0: the picker's Orchestration choice reaches Kriya as the head tier
281
344
  ...(orchestra && { aliases: { [ORCHESTRA_ALIAS]: orchestra.head } }),
345
+ ...(local && { local }),
346
+ ...(own && { routes: own.routes }),
347
+ ...(reporter && { onUsage: reporter.add }),
282
348
  // A Kriya deployed after launch is picked up without a restart
283
349
  checkSupport: async () => ((await models(device.url, device.token)).bodyEncodings ?? []).includes(BODY_ENCODING),
284
350
  log: (text) => process.stderr.write(`kriya: ${text}\n`),
@@ -296,7 +362,7 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
296
362
  // stdout: the answer (kriya run) and ACP's protocol frames pass untouched;
297
363
  // the Web UI's stdout carries only log lines, rebranded like stderr
298
364
  stdio: ["inherit", profile === "kriya" ? "pipe" : "inherit", "pipe"],
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)),
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),
300
366
  })
301
367
  let explained = null
302
368
  const filter = htmlFilter((text) => process.stderr.write(rebrand(text)))
@@ -329,7 +395,8 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
329
395
  filter.end()
330
396
  explained ??= filter.explained
331
397
  if (explained) process.stderr.write(`kriya: ${explained}\n`)
332
- 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)))
333
400
  })
334
401
  })
335
402
  }