@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.
@@ -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,15 +146,47 @@ 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
+
147
181
  /** The launch variable naming the switches the person set themself (a flag, or the variable in their shell) */
148
182
  export const SET_BY_PERSON = "KRIYA_SWITCHES_SET"
149
183
 
150
184
  /** Takes the switch flags out of `args` and sets each switch to "on" or "off" in `env`. */
151
- export function switchEnv(args, env = process.env) {
185
+ export function switchEnv(args, env = process.env, saved = savedSwitches()) {
152
186
  const chosen = new Set((env[SET_BY_PERSON] ?? "").split(",").filter(Boolean))
153
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"
154
190
  if (env[name] === "on" || env[name] === "off") chosen.add(flag)
155
191
  let value = env[name] === "on" ? true : env[name] === "off" ? false : byDefault
156
192
  for (const [form, on] of [[`--${flag}`, true], [`--no-${flag}`, false]]) {
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
 
@@ -0,0 +1,176 @@
1
+ import { createHash } from "node:crypto"
2
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+
5
+ import { kriyaHome } from "./paths.js"
6
+
7
+ // Own models (Kriya-Tavi docs/kriya-harness/OWN_MODELS.md): the person's own
8
+ // API keys for OpenAI-compatible providers, and their own orchestration (head
9
+ // and worker from Kriya's tiers, their own models and the S-1 local model).
10
+ // Keys live only in ~/.kriya/own-models.json (mode 600) and in the launcher's
11
+ // memory for the relay. They never go to Kriya, a log, the Web UI (last four
12
+ // characters only), DSH's process (hashes only, for redaction) or a model.
13
+
14
+ export class OwnModelsError extends Error {}
15
+
16
+ export const PROVIDERS = [
17
+ { id: "openrouter", name: "OpenRouter", url: "https://openrouter.ai/api/v1", keys: "https://openrouter.ai/settings/keys" },
18
+ { id: "openai", name: "OpenAI", url: "https://api.openai.com/v1", keys: "https://platform.openai.com/api-keys" },
19
+ { id: "deepseek", name: "DeepSeek", url: "https://api.deepseek.com/v1", keys: "https://platform.deepseek.com/api_keys" },
20
+ { id: "groq", name: "Groq", url: "https://api.groq.com/openai/v1", keys: "https://console.groq.com/keys" },
21
+ { id: "together", name: "Together AI", url: "https://api.together.xyz/v1", keys: "https://api.together.xyz/settings/api-keys" },
22
+ { id: "mistral", name: "Mistral", url: "https://api.mistral.ai/v1", keys: "https://console.mistral.ai/api-keys" },
23
+ { id: "custom", name: "Custom (OpenAI-compatible)", url: null, keys: null },
24
+ ]
25
+
26
+ export const KEY = /^[\x21-\x7e]{8,400}$/
27
+ export const MODEL = /^[\w.:\/@+-]{1,120}$/
28
+ export const MAX_MODELS = 12
29
+ const TIERS = ["balanced", "budget", "escalation"]
30
+ export const DEFAULT_CONTEXT = 131_072
31
+ const clampContext = (n) => Math.min(2_000_000, Math.max(16_384, Number.isSafeInteger(n) ? n : DEFAULT_CONTEXT))
32
+
33
+ export const ownFile = (home = kriyaHome()) => join(home, "own-models.json")
34
+
35
+ const empty = () => ({ version: 1, keys: {}, models: [], orchestra: null })
36
+
37
+ /** The stored setup; an empty one when the file is missing or broken */
38
+ export function readOwn(file = ownFile()) {
39
+ try {
40
+ const v = JSON.parse(readFileSync(file, "utf8"))
41
+ return {
42
+ version: 1,
43
+ keys: v.keys && typeof v.keys === "object" ? Object.fromEntries(Object.entries(v.keys).filter(([p, k]) => PROVIDERS.some((x) => x.id === p) && typeof k?.key === "string" && KEY.test(k.key))) : {},
44
+ models: Array.isArray(v.models) ? v.models.filter((m) => typeof m?.id === "string" && MODEL.test(m.model ?? "") && v.keys?.[m.provider]).slice(0, MAX_MODELS) : [],
45
+ orchestra: v.orchestra && typeof v.orchestra.head === "string" && typeof v.orchestra.worker === "string" ? { head: v.orchestra.head, worker: v.orchestra.worker } : null,
46
+ }
47
+ } catch {
48
+ return empty()
49
+ }
50
+ }
51
+
52
+ function write(state, file) {
53
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
54
+ const tmp = `${file}.${process.pid}.tmp`
55
+ writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
56
+ chmodSync(tmp, 0o600)
57
+ renameSync(tmp, file)
58
+ return state
59
+ }
60
+
61
+ /** A custom endpoint: https only, no credentials in the address */
62
+ export function customUrl(value) {
63
+ let url
64
+ try {
65
+ url = new URL(String(value ?? "").trim())
66
+ } catch {
67
+ throw new OwnModelsError("That isn't an address. A custom provider is an https URL ending at its API, e.g. https://api.example.com/v1.")
68
+ }
69
+ if (url.protocol !== "https:") throw new OwnModelsError("A custom provider must use https. For a model on this computer, use --local-model.")
70
+ if (url.username || url.password || url.search || url.hash) throw new OwnModelsError("Put the key in the key field, not in the address.")
71
+ return url.href.replace(/\/+$/, "")
72
+ }
73
+
74
+ export const providerUrl = (provider, stored) => PROVIDERS.find((p) => p.id === provider)?.url ?? stored?.url ?? null
75
+
76
+ export function saveKey(provider, key, url, file = ownFile()) {
77
+ if (!PROVIDERS.some((p) => p.id === provider)) throw new OwnModelsError("Kriya doesn't know that provider.")
78
+ const k = String(key ?? "").trim()
79
+ if (!KEY.test(k)) throw new OwnModelsError("That doesn't look like an API key (8 to 400 characters, no spaces).")
80
+ const state = readOwn(file)
81
+ state.keys[provider] = { key: k, ...(provider === "custom" && { url: customUrl(url) }) }
82
+ return write(state, file)
83
+ }
84
+
85
+ /** Removes a provider's key, its models, and an orchestration that used them */
86
+ export function removeKey(provider, file = ownFile()) {
87
+ const state = readOwn(file)
88
+ delete state.keys[provider]
89
+ const gone = new Set(state.models.filter((m) => m.provider === provider).map((m) => m.id))
90
+ state.models = state.models.filter((m) => !gone.has(m.id))
91
+ if (state.orchestra && (gone.has(state.orchestra.head) || gone.has(state.orchestra.worker))) state.orchestra = null
92
+ return write(state, file)
93
+ }
94
+
95
+ export function addModel(provider, model, contextWindow, file = ownFile()) {
96
+ const state = readOwn(file)
97
+ if (!state.keys[provider]) throw new OwnModelsError("Add that provider's key first.")
98
+ if (!MODEL.test(String(model ?? ""))) throw new OwnModelsError("That isn't a model id.")
99
+ if (state.models.some((m) => m.provider === provider && m.model === model)) return state
100
+ if (state.models.length >= MAX_MODELS) throw new OwnModelsError(`At most ${MAX_MODELS} of your own models; remove one first.`)
101
+ const n = Math.max(0, ...state.models.map((m) => Number(/-(\d+)$/.exec(m.id)?.[1] ?? 0))) + 1
102
+ state.models.push({ id: `own-${n}`, provider, model, contextWindow: clampContext(contextWindow) })
103
+ return write(state, file)
104
+ }
105
+
106
+ export function removeModel(id, file = ownFile()) {
107
+ const state = readOwn(file)
108
+ state.models = state.models.filter((m) => m.id !== id)
109
+ if (state.orchestra && (state.orchestra.head === id || state.orchestra.worker === id)) state.orchestra = null
110
+ return write(state, file)
111
+ }
112
+
113
+ /** The person's orchestration: head and worker, each a Kriya tier, one of their models, or "local"; null clears it */
114
+ export function setOrchestra(choice, file = ownFile()) {
115
+ const state = readOwn(file)
116
+ if (choice === null) return write({ ...state, orchestra: null }, file)
117
+ const ok = (id) => TIERS.includes(id) || id === "local" || state.models.some((m) => m.id === id)
118
+ if (!ok(choice?.head) || !ok(choice?.worker)) throw new OwnModelsError("Choose the head and the worker from the lists.")
119
+ if (choice.head === choice.worker) throw new OwnModelsError("The head and the worker must be different models.")
120
+ if (choice.head === "local") throw new OwnModelsError("The local model builds; the head plans, so choose a stronger model for it.")
121
+ return write({ ...state, orchestra: { head: choice.head, worker: choice.worker } }, file)
122
+ }
123
+
124
+ // Short in the model picker: "Custom", not "Custom (OpenAI-compatible)"
125
+ const label = (m) => `${m.provider === "custom" ? "Custom" : (PROVIDERS.find((p) => p.id === m.provider)?.name ?? m.provider)} · ${m.model}`.slice(0, 80)
126
+
127
+ /** What the Web UI may see: no key, only its last four characters */
128
+ export function publicView(file = ownFile()) {
129
+ const s = readOwn(file)
130
+ return {
131
+ providers: PROVIDERS.map((p) => ({ id: p.id, name: p.name, keysUrl: p.keys, saved: Boolean(s.keys[p.id]), ...(s.keys[p.id] && { last4: s.keys[p.id].key.slice(-4) }), ...(p.id === "custom" && s.keys.custom?.url && { url: s.keys.custom.url }) })),
132
+ models: s.models.map((m) => ({ id: m.id, provider: m.provider, model: m.model, name: label(m), contextWindow: m.contextWindow })),
133
+ orchestra: s.orchestra,
134
+ }
135
+ }
136
+
137
+ /** The provider's models (GET <url>/models with the person's key), with context windows where the provider says */
138
+ export async function listProviderModels(provider, file = ownFile(), fetchImpl = fetch) {
139
+ const s = readOwn(file)
140
+ const stored = s.keys[provider]
141
+ if (!stored) throw new OwnModelsError("Add that provider's key first.")
142
+ const url = providerUrl(provider, stored)
143
+ let answer
144
+ try {
145
+ answer = await fetchImpl(`${url}/models`, { headers: { authorization: `Bearer ${stored.key}`, accept: "application/json" }, signal: AbortSignal.timeout(15_000), redirect: "error" })
146
+ } catch {
147
+ throw new OwnModelsError(`Couldn't reach ${new URL(url).host}.`)
148
+ }
149
+ if (answer.status === 401 || answer.status === 403) throw new OwnModelsError("The provider refused that key. Check it and save it again.")
150
+ if (!answer.ok) throw new OwnModelsError(`The provider answered ${answer.status}.`)
151
+ const body = await answer.json().catch(() => ({}))
152
+ const list = Array.isArray(body?.data) ? body.data : []
153
+ return list
154
+ .filter((m) => typeof m?.id === "string" && MODEL.test(m.id))
155
+ .map((m) => ({ id: m.id, ...(Number.isSafeInteger(m.context_length) && { contextWindow: m.context_length }) }))
156
+ .sort((a, b) => a.id.localeCompare(b.id))
157
+ .slice(0, 2000)
158
+ }
159
+
160
+ /** sha256 of each saved key: DSH's redactor gets these, never a key */
161
+ export const keyHashes = (file = ownFile()) => Object.values(readOwn(file).keys).map((k) => createHash("sha256").update(k.key).digest("hex"))
162
+
163
+ /**
164
+ * What a launch uses, only with the owner's harness.ownModels: the models the
165
+ * picker lists (no key, no address), the relay's routes (with keys, launcher
166
+ * memory only) and the person's orchestration when every part of it is usable.
167
+ * @param {{ allowed: string[], local?: boolean }} opts
168
+ */
169
+ export function launchOwn(file = ownFile(), { allowed = TIERS, local = false } = {}) {
170
+ const s = readOwn(file)
171
+ const models = s.models.map((m) => ({ id: m.id, name: label(m), contextWindow: clampContext(m.contextWindow) }))
172
+ const routes = Object.fromEntries(s.models.map((m) => [m.id, { url: providerUrl(m.provider, s.keys[m.provider]), model: m.model, key: s.keys[m.provider].key, provider: m.provider }]))
173
+ const usable = (id) => allowed.includes(id) || Boolean(routes[id]) || (id === "local" && local)
174
+ const orchestra = s.orchestra && usable(s.orchestra.head) && usable(s.orchestra.worker) ? s.orchestra : undefined
175
+ return { models, routes, ...(orchestra && { orchestra }), hashes: keyHashes(file) }
176
+ }
@@ -0,0 +1,63 @@
1
+ import { call, KriyaError } from "./api.js"
2
+
3
+ // Own models (Kriya-Tavi docs/kriya-harness/OWN_MODELS.md): the counts of
4
+ // calls through the person's own keys (and S-1's local model), sent to Kriya
5
+ // in batches: provider, model, requests, tokens and the provider's reported
6
+ // cost. Never a prompt, an answer or a key. Kriya answering 404 means the
7
+ // owner's harness.ownModels is off: reporting stops for this run.
8
+
9
+ export const FLUSH_MS = 30_000
10
+ const MAX_BATCH = 50
11
+ const MAX_KEYS = 500
12
+
13
+ /**
14
+ * @param {{ device: { url: string, token: string }, post?: (body: any) => Promise<any>, every?: number, log?: (text: string) => void }} options
15
+ */
16
+ export function usageReporter({ device, post = (body) => call(device.url, "POST", "/own-usage", { token: device.token, body }), every = FLUSH_MS, log = () => {} }) {
17
+ const pending = new Map()
18
+ let stopped = false
19
+ let flushing = null
20
+ const add = (e) => {
21
+ if (stopped || !e?.provider || !e?.model) return
22
+ const key = `${e.provider}\0${e.model}`
23
+ const now = pending.get(key) ?? { provider: e.provider, model: String(e.model).slice(0, 120), requests: 0, inputTokens: 0, outputTokens: 0 }
24
+ now.requests += e.requests ?? 1
25
+ now.inputTokens += e.inputTokens ?? 0
26
+ now.outputTokens += e.outputTokens ?? 0
27
+ // A cost only while every call so far reported one: a partial sum would understate
28
+ if (e.reportedCostMicroUsd !== undefined && (now.requests === (e.requests ?? 1) || now.reportedCostMicroUsd !== undefined)) now.reportedCostMicroUsd = (now.reportedCostMicroUsd ?? 0) + e.reportedCostMicroUsd
29
+ else delete now.reportedCostMicroUsd
30
+ if (pending.size < MAX_KEYS || pending.has(key)) pending.set(key, now)
31
+ }
32
+ const flush = () =>
33
+ (flushing ??= (async () => {
34
+ while (!stopped && pending.size) {
35
+ const batch = [...pending.values()].slice(0, MAX_BATCH)
36
+ for (const e of batch) pending.delete(`${e.provider}\0${e.model}`)
37
+ try {
38
+ await post({ entries: batch.map((e) => ({ ...e, requests: Math.min(e.requests, 10_000) })) })
39
+ } catch (error) {
40
+ if (error instanceof KriyaError && error.status === 404) {
41
+ stopped = true
42
+ pending.clear()
43
+ return
44
+ }
45
+ // Kept for the next try, bounded
46
+ for (const e of batch) if (pending.size < MAX_KEYS) pending.set(`${e.provider}\0${e.model}`, e)
47
+ log(`own-model usage not sent yet (${error?.code ?? error?.message ?? "error"}); will retry`)
48
+ return
49
+ }
50
+ }
51
+ })().finally(() => (flushing = null)))
52
+ const timer = setInterval(flush, every)
53
+ timer.unref?.()
54
+ return {
55
+ add,
56
+ flush,
57
+ pending: () => [...pending.values()],
58
+ close: () => {
59
+ clearInterval(timer)
60
+ return flush()
61
+ },
62
+ }
63
+ }
package/src/profiles.js CHANGED
@@ -51,6 +51,10 @@ export const LINKED = {
51
51
  "@kriya-ai/harness-router": join(PACKAGE_ROOT, "plugins", "router"),
52
52
  "@kriya-ai/harness-projects": join(PACKAGE_ROOT, "plugins", "projects"),
53
53
  "@kriya-ai/harness-fs-freshness": join(PACKAGE_ROOT, "plugins", "fs-freshness"),
54
+ "@kriya-ai/harness-directory-picker": join(PACKAGE_ROOT, "plugins", "directory-picker"),
55
+ "@kriya-ai/harness-cockpit": join(PACKAGE_ROOT, "plugins", "cockpit"),
56
+ "@kriya-ai/harness-providers": join(PACKAGE_ROOT, "plugins", "providers"),
57
+ "@kriya-ai/harness-keyguard": join(PACKAGE_ROOT, "plugins", "keyguard"),
54
58
  "@kriya-ai/harness-loop": join(PACKAGE_ROOT, "plugins", "loop"),
55
59
  "@kriya-ai/harness-budget": join(PACKAGE_ROOT, "plugins", "budget"),
56
60
  "@kriya-ai/harness-grounding": join(PACKAGE_ROOT, "plugins", "grounding"),
package/src/proof.js ADDED
@@ -0,0 +1,78 @@
1
+ // S-3 (Kriya-Tavi docs/kriya-harness/TASK_PROOF.md; owner decisions 2026-11-24):
2
+ // what a task started from Kriya reports back, computed by code on this
3
+ // computer. The verdict, each step's attempts, who built each attempt and the
4
+ // gates come from the loop's own ledger (verify.js verdict), never from model
5
+ // text. Changes are file names with line counts: no code leaves the computer.
6
+
7
+ import { snapshot, trackedRoot, treeChanges } from "./checkpoints.js"
8
+ import { stepLabel, verdict } from "./verify.js"
9
+
10
+ const GATE = /^G-[A-Z0-9-]{2,20}$/
11
+ export const MAX_FILES = 200
12
+
13
+ const modelNames = (env) => {
14
+ try {
15
+ return JSON.parse(env.KRIYA_MODEL_NAMES || "{}")
16
+ } catch {
17
+ return {}
18
+ }
19
+ }
20
+
21
+ /** The steps' proof from a progress ledger, or undefined without a plan */
22
+ export function stepsProof(progress, env = process.env) {
23
+ const plan = progress?.plan
24
+ if (!plan?.steps?.length) return undefined
25
+ const ledger = { ...progress, runs: progress.runs ?? [] }
26
+ const v = verdict(ledger)
27
+ const named = modelNames(env)
28
+ const head = env.KRIYA_ORCHESTRA_HEAD
29
+ const who = (tier) => ({
30
+ level: head && env.KRIYA_ORCHESTRA === "on" ? (tier === head ? "head" : "worker") : "single",
31
+ name: String(named[tier] ?? `Kriya ${tier}`).slice(0, 80),
32
+ ...(tier === "local" && { local: true }),
33
+ })
34
+ const steps = plan.steps.map((step, i) => {
35
+ const label = stepLabel(plan, i + 1)
36
+ const found = v.steps.find((s) => s.step === label)
37
+ const last = ledger.runs.findLast((r) => r.step === label)
38
+ return {
39
+ n: i + 1,
40
+ title: String(step.title ?? "").slice(0, 120),
41
+ verdict: found?.status ?? "not run",
42
+ attempts: found?.attempts ?? 0,
43
+ builtBy: (progress.builders ?? []).filter((b) => b.step === label && !b.polish && typeof b.tier === "string" && b.tier).slice(0, 8).map((b) => who(b.tier)),
44
+ gates: (last?.gates ?? []).filter((g) => GATE.test(g?.id ?? "")).slice(0, 20).map((g) => ({ id: g.id, status: String(g.status).slice(0, 20) })),
45
+ }
46
+ })
47
+ return { verdict: v.status, steps: steps.slice(0, 12), ...(v.touched?.length && { touchedChecks: v.touched.slice(0, 20).map((p) => String(p).slice(0, 300)) }) }
48
+ }
49
+
50
+ /** The folder's working tree before a task, or null where it can't be read */
51
+ export async function baseline(folder) {
52
+ try {
53
+ const tracked = await trackedRoot(folder)
54
+ return tracked ? { root: tracked.root, tree: await snapshot(tracked.root) } : null
55
+ } catch {
56
+ return null
57
+ }
58
+ }
59
+
60
+ /** Files changed since `base`: names, status and line counts only */
61
+ export async function changesSince(base) {
62
+ if (!base) return null
63
+ try {
64
+ const files = await treeChanges(base.root, base.tree, await snapshot(base.root))
65
+ const total = files.reduce((t, f) => ({ added: t.added + (f.added ?? 0), deleted: t.deleted + (f.deleted ?? 0) }), { added: 0, deleted: 0 })
66
+ return {
67
+ files: files.slice(0, MAX_FILES).map((f) => ({
68
+ path: String(f.path).slice(0, 300),
69
+ status: f.status,
70
+ ...(f.binary ? { binary: true } : { added: f.added ?? 0, deleted: f.deleted ?? 0 }),
71
+ })),
72
+ count: files.length,
73
+ ...total,
74
+ }
75
+ } catch {
76
+ return null
77
+ }
78
+ }